package com.gamota.mobi.background;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

import main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.gamota.mobi.R;
import com.gamota.mobi.db.DatabaseHelper;
import com.gamota.mobi.download.http.MyHttpClient;
import com.gamota.mobi.event.Event;
import com.gamota.mobi.event.Event.RequestFailEvent;
import com.gamota.mobi.model.AccessToken;
import com.gamota.mobi.model.AppStoreVnApplicationInfo;
import com.gamota.mobi.model.AppStoreVnUpdateData;
import com.gamota.mobi.model.BankOption;
import com.gamota.mobi.model.BankPayment;
import com.gamota.mobi.model.BannerItem;
import com.gamota.mobi.model.CategoryItem;
import com.gamota.mobi.model.CollectionGroup;
import com.gamota.mobi.model.CollectionList;
import com.gamota.mobi.model.CommentItem;
import com.gamota.mobi.model.ContentItemInfo;
import com.gamota.mobi.model.ContentItemInfo.RelatedItem;
import com.gamota.mobi.model.ContentItemInfo.Version;
import com.gamota.mobi.model.DownloadLink;
import com.gamota.mobi.model.ExchangeTymData;
import com.gamota.mobi.model.FBFeedItem;
import com.gamota.mobi.model.FBFeedItem.FBComments;
import com.gamota.mobi.model.FBFeedItem.FBLikes;
import com.gamota.mobi.model.FBFeedItem.FBUser;
import com.gamota.mobi.model.GiftSetting;
import com.gamota.mobi.model.Giftbox;
import com.gamota.mobi.model.PaypalForm;
import com.gamota.mobi.model.PaypalPayment;
import com.gamota.mobi.model.RecommendItem;
import com.gamota.mobi.model.SMSOption;
import com.gamota.mobi.model.SMSPayment;
import com.gamota.mobi.model.TopupResult;
import com.gamota.mobi.model.UserDownloaded;
import com.gamota.mobi.model.UserInfo;
import com.gamota.mobi.model.UserTransaction;
import com.gamota.mobi.network.HttpUtils;
import com.gamota.mobi.util.Constants;
import com.gamota.mobi.util.Utils;
import com.google.android.gcm.GCMRegistrar;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import de.greenrobot.event.EventBus;

public class ContentNetworkInterface {

	public static final String CLIENT_TYPE = "appstorevn_app";
	public static final String GP_CLIENT = "googleplay";
	private static final int MAX_ATTEMPTS = 5;
	private static final int BACKOFF_MILLI_SECONDS = 2000;
	private static final String HASH_KEY = "daylaappios";
	private static final String TAG = ContentNetworkInterface.class.getSimpleName();
	public static final String SERVER_URL = "https://api.appota.com/client/notification?access_token=";
	// Google project id
	public static final String SENDER_ID = "787730237419";
	public static final String deviceOSName = "Android";
	public static final String deviceOSVersion = Build.MANUFACTURER + " " + Build.PRODUCT + " " + Build.VERSION.RELEASE;
	public static final String ENABLE_FREE_TYM = "_1_means_enable";
	//private long expire = 15 * 60 * 1000;

	private static Context context;
	private String countryCode;
	private EventBus eventBus;
	private static ContentNetworkInterface defaultInstance;
	private AQuery aq;
	public static ContentNetworkInterface getInstance() {
        if (defaultInstance == null) {
            synchronized (ContentNetworkInterface.class) {
                if (defaultInstance == null) {
                    defaultInstance = new ContentNetworkInterface();
                }
            }
        }
        return defaultInstance;
    }
	
	public ContentNetworkInterface init(Context context){
		ContentNetworkInterface.context = context;
		eventBus = EventBus.getDefault();
		aq = new AQuery(context);
		//countryCode = Utils.getStaticCountryCode(context);
		countryCode = "vn";
		return defaultInstance;
	}
	
	public void convertLink(String accessToken, String link){
		String endpoint = Constants.CONVERT_LINK_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("link", link);
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	boolean status;
					try {
						status = json.getBoolean("status");
	                	if(status){
	                		JSONObject data = json.getJSONObject("data");
	                		String store = data.getString("store");
	                		String slug = data.getString("slug");
	                		eventBus.post(new Event.ConvertLinkSuccess(store, slug));
	                	} else {
	                		eventBus.post(new Event.ConvertLinkFail(json.getString("message")));
	                	}
					} catch (JSONException e) {
						e.printStackTrace();
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "Error1: " + ajaxStatus.getCode());
                }
            }
		});
	}
	
	public void getRequestToken(String responseType, String clientKey, String redirectUri, List<String> scopes, String state, String lang) throws UnsupportedEncodingException {
		String scope = "";
		for (String s : scopes) {
			scope += s + ",";
		}
		String params = URLEncoder.encode(Constants.RESPONSE_TYPE_KEY, Constants.ENCODE)
				+ "="
				+ URLEncoder.encode(responseType, Constants.ENCODE)
				+ "&"
				+ URLEncoder.encode(Constants.CLIENT_ID_KEY, Constants.ENCODE)
				+ "="
				+ URLEncoder.encode(clientKey, Constants.ENCODE)
				+ "&"
				+ URLEncoder.encode(Constants.CALLBACK_URL_KEY, Constants.ENCODE)
				+ "="
				+ URLEncoder.encode(redirectUri, Constants.ENCODE)
				+ "&"
				+ URLEncoder.encode(Constants.SCOPE_KEY, Constants.ENCODE)
				+ "="
				+ URLEncoder.encode(scope.substring(0, scope.length() - 1),
						Constants.ENCODE) + "&"
				+ URLEncoder.encode(Constants.STATE_KEY, Constants.ENCODE) + "="
				+ URLEncoder.encode(state, Constants.ENCODE) + "&"
				+ URLEncoder.encode(Constants.LANG_KEY, Constants.ENCODE) + "="
				+ URLEncoder.encode(lang, Constants.ENCODE);
		String endpoint = Constants.REQUEST_TOKEN_ENDPOINT + "?" + params;
		aq.ajax(endpoint, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			String requestToken = json.getString("request_token");
    						eventBus.post(new Event.RequestTokenEvent(requestToken));
                		} else {
                			eventBus.post(new Event.RequestTokenEvent(""));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestTokenEvent(""));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "Error1: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestTokenEvent(""));
                }
            }
		});
	}
	
	public void getAccessToken(String requestToken, String clientKey, String clientSecret, String redirectUri, String grantType, String lang){
		String endpoint = Constants.ACCESS_TOKEN_ENDPOINT;
		Map<String, String> params = new HashMap<String, String>();
		params.put(Constants.REQUEST_TOKEN_KEY, requestToken);
		params.put(Constants.CLIENT_ID_KEY, clientKey);
		params.put(Constants.CLIENT_SECRET_KEY, clientSecret);
		params.put(Constants.CALLBACK_URL_KEY, Constants.DEFAULT_REDIRECT_URI);
		params.put(Constants.GRANT_TYPE_KEY, Constants.GRANT_TYPE);
		params.put(Constants.LANG_KEY, lang);
//		Log.e("NMN","getAccessToken REQUEST_TOKEN_KEY:"+requestToken);
//		Log.e("NMN","getAccessToken CLIENT_ID_KEY:"+clientKey);
//		Log.e("NMN","getAccessToken CLIENT_SECRET_KEY:"+clientSecret);
//		Log.e("NMN","getAccessToken CALLBACK_URL_KEY:"+Constants.DEFAULT_REDIRECT_URI);
//		Log.e("NMN","getAccessToken GRANT_TYPE_KEY:"+Constants.GRANT_TYPE);
//		Log.e("NMN","getAccessToken LANG_KEY:"+lang);
//		Log.e("NMN","getAccessToken url:"+endpoint);
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
//                		Log.e("NMN","getAccessToken response:"+json.toString());
                		boolean status = json.getBoolean("status");
                		if(status){
                			Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
                			AccessToken accessToken = gson.fromJson(json.toString(), AccessToken.class);
                			eventBus.post(new Event.GetAccessTokenSuccessEvent(accessToken));
                		} else {
                			eventBus.post(new Event.GetAccessTokenFailEvent(json.getInt("error_code")));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.GetAccessTokenFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "Error2: getAccessToken" + ajaxStatus.getCode());
                	eventBus.post(new Event.GetAccessTokenFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void refreshToken(String token, String clientKey, String clientSecret){
		String endpoint = Constants.REFRESH_TOKEN_ENDPOINT;
		Map<String, String> params = new HashMap<String, String>();
		params.put(Constants.REFRESH_TOKEN_KEY, token);
		params.put(Constants.CLIENT_ID_KEY, clientKey);
		params.put(Constants.CLIENT_SECRET_KEY, clientSecret);
		params.put(Constants.GRANT_TYPE_KEY, "refresh_token");
		
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
                			AccessToken accessToken = gson.fromJson(json.toString(), AccessToken.class);
                			eventBus.post(new Event.GetAccessTokenSuccessEvent(accessToken));
                		} else {
                			eventBus.post(new Event.GetAccessTokenFailEvent(json.getInt("error_code")));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.GetAccessTokenFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + "refreshToken:" + json.toString());
                } else {
                	Log.e(TAG, "Error3: refreshToken" + ajaxStatus.getCode());
                	eventBus.post(new Event.GetAccessTokenFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void login(Context context, String oldAccessToken, String username, String password){
		String endpoint = Constants.LOGIN_ENDPOINT + oldAccessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("username", username);
		params.put("password", password);
		params.put("device_id", Utils.getDeviceId(context));
		params.put("device_os", deviceOSName);
		params.put("device_os_version", deviceOSVersion);
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
                			AccessToken accessToken = gson.fromJson(json.toString(), AccessToken.class);
                			eventBus.post(new Event.LoginSuccessEvent(accessToken));
                		} else {
                			eventBus.post(new Event.LoginFailEvent(json.getString("message")));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.LoginFailEvent("-2"));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "login Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.LoginFailEvent(ajaxStatus.getCode() + ""));
                }
            }
		});
	}
	
	public void logout(String accessToken){
		String endpoint = Constants.LOGOUT_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("access_token", accessToken);
		aq.ajax(endpoint,params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			eventBus.post(new Event.LogoutEvent(status));
                		} else {
                			eventBus.post(new Event.LogoutFailed());
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "logout Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void register(Context context, String accessToken, String username, String password, String email){
		String endpoint = Constants.REGISTER_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("username", username);
		params.put("password", password);
		params.put("email", email);
		params.put("device_id", Utils.getDeviceId(context));
		params.put("device_os", deviceOSName);
		params.put("device_os_version", deviceOSVersion);
		
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	Log.e("register", "register res:"+json.toString());
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			eventBus.post(new Event.RegisterSuccessEvent());
                		} else {
                			eventBus.post(new Event.RegisterFailedEvent(json.getString("message")));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "register Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}

	public void getUserInfo(String accessToken) {
		String endpoint = Constants.USER_INFO_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		if(accessToken.equalsIgnoreCase("3de71f9e84a325bbfb86466c15b40b1e")){
			return;
		}
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			JSONObject obj = json.getJSONObject("data");
                			UserInfo user = new UserInfo();
                			user.setAvatarUr(obj.getString("avatar"));
//                			user.setBirthday(obj.getString("birthday"));
                			user.setFullName(obj.getString("fullname"));
                			user.setUserName(obj.getString("username"));
                			user.setGender(obj.getString("gender"));
                			user.setEmail(obj.getString("email"));
//                			user.setGreenTym(obj.getInt("blue_tym"));
//                			user.setPurpleTym(obj.getInt("purple_tym"));
//                			user.setYellowTym(obj.getInt("yellow_tym"));
                			eventBus.post(new Event.UserInfoSuccessEvent(user));
                		} else {
                			eventBus.post(new Event.UserInfoFailEvent(json.getInt("error_code")));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.UserInfoFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "Get User info Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.UserInfoFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}

	public void getCategoryList(String accessToken, int storeId, String type) {
		String lang = Locale.getDefault().getLanguage();
		if (!lang.equalsIgnoreCase("vi")) {
			lang = "en";
		}
		String endpoint = Constants.CATEGORY_ENDPOINT + accessToken + "&lang=" + lang;
		Map<String, String> params = new HashMap<String, String>();
		params.put("store_id", String.valueOf(storeId));
		params.put("type", type);
		if (countryCode.equalsIgnoreCase("vn")) {
			params.put("client", CLIENT_TYPE);
		} else {
			params.put("client", GP_CLIENT);
		}
		final List<CategoryItem> list = new ArrayList<CategoryItem>();
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
                			JSONArray jsonArray = json.getJSONArray("data");
                			CategoryItem cat = null;
                			for(int i=0; i< jsonArray.length(); i++){
                				JSONObject obj = jsonArray.getJSONObject(i);
                				cat = gson.fromJson(obj.toString(), CategoryItem.class);
                				if(cat.getCategoryName().equalsIgnoreCase("games")){
                					continue;
                				}
                				list.add(cat);
                			}
                			eventBus.post(new Event.CategoryListSuccessEvent(list));
                		} else {
                			eventBus.post(new Event.RequestFailEvent(json.getInt("error_code")));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "get category list Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}

	public void getAllBanners(String accessToken, String store, final String page, final String where) {
		String endpoint = Constants.BANNER_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("store", store);
		params.put("page", page);
		if (countryCode.equalsIgnoreCase("vn")) {
			params.put("client", "android_gamota");//
		} else {
			params.put("client", GP_CLIENT);
		}
//		Log.e("NMN","getAllBanners url:"+endpoint);
//		Log.e("NMN","getAllBanners store:"+store);
//		Log.e("NMN","getAllBanners page:"+page);
//		Log.e("NMN","getAllBanners client:"+countryCode);
		final Map<String, BannerItem> bannerList = new HashMap<String, BannerItem>();
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			if(page.equalsIgnoreCase(Constants.AD_START_SCREEN)){
                				JSONObject obj = json.getJSONObject("data");
                				Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
                				BannerItem banner = gson.fromJson(obj.toString(), BannerItem.class);
                				if (!bannerList.containsKey(Constants.AD_START_SCREEN + 0)) {
        							bannerList.put(Constants.AD_START_SCREEN + 0, banner);
        						} else {
        							bannerList.put(Constants.AD_START_SCREEN + 0 + "-1", banner);
        						}
                				if(bannerList.size() > 0){
                					eventBus.post(new Event.AllBannerSuccessEvent(bannerList, where));
                				} else {
                					eventBus.post(new Event.NoStartScreenBannerEvent());
                				}
                			} else {
                				JSONArray array = json.getJSONArray("data");
                				Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
                				BannerItem banner = null;
                				if(array.length() > 0){
                					for(int i=0; i<array.length();i++){
                    					JSONObject bannerObj = array.getJSONObject(i);
                    					banner = gson.fromJson(bannerObj.toString(), BannerItem.class);
                    					if (!bannerList.containsKey(banner.getSection() + banner.getPosition())) {
            								bannerList.put(banner.getSection() + banner.getPosition(), banner);
            							}
                    				}
                    				eventBus.post(new Event.AllBannerSuccessEvent(bannerList, where));
                				} else {
                					eventBus.post(new Event.GetBannerFailEvent(where));
                				}
                			}
                		} else {
                			eventBus.post(new Event.NoStartScreenBannerEvent());
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "get all banners Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void getTextBanners(String accessToken, String store, final String where){
		String endpoint = Constants.BANNER_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		if(store.equalsIgnoreCase("home") || store.equalsIgnoreCase("apps") || store.equalsIgnoreCase("games")){
			store = "android";
		}
		params.put("store", "android_gamota");
		params.put("page", Constants.AD_TEXT);
		if (countryCode.equalsIgnoreCase("vn")) {
			params.put("client", "android_gamota");
		} else {
			params.put("client", GP_CLIENT);
		}
		final List<BannerItem> bannerList = new ArrayList<BannerItem>();
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	Log.e("getBann","getBann: "+json.toString());
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			JSONArray array = json.getJSONArray("data");
            				Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
            				BannerItem banner = null;
            				for(int i=0; i<array.length();i++){
            					JSONObject bannerObj = array.getJSONObject(i);
            					banner = gson.fromJson(bannerObj.toString(), BannerItem.class);
            					bannerList.add(banner);
            				}
            				eventBus.post(new Event.PageBannerSuccessEvent(bannerList, where));
                		} else {
//                			eventBus.post(new Event.GetBannerFailEvent(where));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
//						eventBus.post(new Event.RequestFailEvent(-2,where));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "get text banners Error: " + ajaxStatus.getCode());
//                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode(),where));
                }
            }
		});
	}
	
	public void getBannerByPage(String accessToken, String store, final String page){
		String endpoint = Constants.BANNER_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("store", store);
		params.put("page", page);
		if (countryCode.equalsIgnoreCase("vn")) {
			params.put("client", CLIENT_TYPE);
		} else {
			params.put("client", GP_CLIENT);
		}
		final List<BannerItem> bannerList = new ArrayList<BannerItem>();
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			JSONArray array = json.getJSONArray("data");
            				Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
            				BannerItem banner = null;
            				for(int i=0; i<array.length();i++){
            					JSONObject bannerObj = array.getJSONObject(i);
            					banner = gson.fromJson(bannerObj.toString(), BannerItem.class);
            					bannerList.add(banner);
            				}
            				eventBus.post(new Event.PageBannerSuccessEvent(bannerList, ""));
                		} else {
                			eventBus.post(new Event.RequestFailEvent(json.getInt("error_code")));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "get banner by page Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}

	public void getTopContent(final String type, int cateId, String accessToken, int storeId, final int start) {
		String endpoint = "";
		String client;
		String filter;
		String version = "android_" + getAppVersion(context);
		countryCode = Utils.getStaticCountryCode(context);
		final DatabaseHelper db = new DatabaseHelper(context);
		Map<String, String> params = new HashMap<String, String>();
		if (type.contains("Newest")) {
			endpoint = Constants.TOPNEW_ENDPOINT + accessToken;
			params.put("store_id", String.valueOf(storeId));
		} else if (type.equalsIgnoreCase(context.getResources().getString(R.string.top_download))) {
			endpoint = Constants.TOPDOWNLOAD_ENDPOINT + accessToken;
			params.put("store_id", String.valueOf(storeId));
		} else if (type.equalsIgnoreCase(context.getResources().getString(R.string.top_paid))) {
			endpoint = Constants.TOPPAID_ENDPOINT + accessToken;
			params.put("store_id", String.valueOf(storeId));
		} else if (type.contains("Top Free")) {// using for featured
			endpoint = "https://api.appota.com/content/featured?access_token=" + accessToken+"&lang=en";
			params.put("store_id", String.valueOf(storeId));
		} else if (type.contains("Hot")) {
			endpoint = Constants.HOT_ENDPOINT + accessToken;
			params.put("store", String.valueOf(storeId));
		}
		if (cateId != 0 && type.contains("Hot")) {//for featured
			params.put("category", String.valueOf(cateId));
		}else if(cateId != 0){
			params.put("category_id", String.valueOf(cateId));
		}
		params.put("start", String.valueOf(start));
		if (countryCode.equalsIgnoreCase("vn")) {
			client = CLIENT_TYPE;
			params.put("client", "gamota");
		} else {
			client = GP_CLIENT;
			params.put("client", "gamota");
		}
		if (Utils.isTablet(context)) {
			filter = "has_tablet";
			params.put("filter", "has_tablet");
		} else {
			params.put("filter", "no_tablet");
			filter = "no_tablet";
		}
		params.put("limit", "20");
		String input = cateId + client + filter + "20" + start + storeId + version + "AppStoreVnAndroidNative!@#";
		String hash = Utils.generateHashMD5(input);
		params.put("hash", hash);
		params.put("v", version);
		Log.e("getTopContent","getTopContent url: "+endpoint+" for "+type);
		final List<ContentItemInfo> listContent = new ArrayList<ContentItemInfo>();
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		Log.e("getTopContent","getTopContent: "+json.toString());
                		boolean status = json.getBoolean("status");
                		if(status){
                			Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
                			JSONArray jsonArray = json.getJSONArray("data");
                			ContentItemInfo item = null;
                			if(jsonArray.length() > 0){
                				for(int i=0; i< jsonArray.length(); i++){
                    				JSONObject obj = jsonArray.getJSONObject(i);
                    				item = gson.fromJson(obj.toString(), ContentItemInfo.class);
                    				item.setPrice(obj.getInt("price"));
                    				item.setPrice2(obj.getInt("price_2"));
                    				if(obj.has("bought")){
                    					item.setBought(obj.getInt("bought"));
                    				}
                    				if(obj.has("is_bought")){
                    					item.setBought(obj.getInt("is_bought"));
                    				}
                    				if(obj.has("has_promotion")){
                    					item.setHasPromotion(obj.getInt("has_promotion"));
                    				}
                    				if(db.checkAppInstalled(item.getPackageName())){
                    					item.setInstalled(true);
                    				} else {
                    					item.setInstalled(false);
                    				}
                    				listContent.add(item);
                    			}
                    			eventBus.post(new Event.TopContentSuccessEvent(listContent, type));
                			} else {
                				if(start == 0){
                					eventBus.post(new Event.TopNoContentEvent(type));
                				} else {
                					eventBus.post(new Event.TopEndOfContentEvent(type));
                				}
                			}
                		} else {
                			eventBus.post(new Event.GetTopFailEvent(json.getInt("error_code"), type));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.GetTopFailEvent(-2, type));
					}
                    Log.d(TAG, ajaxStatus.getCode() + type + " :" + json.toString());
                } else {
                	Log.e(TAG, "get top content Error: " + ajaxStatus.getCode() + " " + ajaxStatus.getMessage());
                	eventBus.post(new Event.GetTopFailEvent(ajaxStatus.getCode(), type));
                }
            }
		});
	}

	public void searchAll(String accessToken, final int storeId, String keyword, int start) {
		String endpoint = Constants.SEARCH_ENDPOINT + accessToken;
		final DatabaseHelper db = new DatabaseHelper(context);
		countryCode = Utils.getStaticCountryCode(context);
		Map<String, String> params = new HashMap<String, String>();
		params.put("store_id", String.valueOf(storeId));
		params.put("keyword", keyword);
		params.put("start", String.valueOf(start));
		if (countryCode.equalsIgnoreCase("vn")) {
			params.put("client", "gamota");
		} else {
			params.put("client", GP_CLIENT);
		}
		params.put("limit", "20");
		final List<ContentItemInfo> listContent = new ArrayList<ContentItemInfo>();
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	Log.e("search","result: "+json.toString());
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
                			JSONArray jsonArray = json.getJSONArray("data");
                			ContentItemInfo item = null;
                			for(int i=0; i< jsonArray.length(); i++){
                				JSONObject obj = jsonArray.getJSONObject(i);
                				item = gson.fromJson(obj.toString(), ContentItemInfo.class);
                				item.setPackageName(obj.getString("bundle_id"));
                				item.setPrice(obj.getInt("price"));
                				item.setPrice2(obj.getInt("price_2"));
                				if(obj.has("bought")){
                					item.setBought(obj.getInt("bought"));
                				}
                				if(obj.has("has_promotion")){
                					item.setHasPromotion(obj.getInt("has_promotion"));
                				}
                				if(db.checkAppInstalled(item.getPackageName())){
                					item.setInstalled(true);
                				} else {
                					item.setInstalled(false);
                				}
                				listContent.add(item);
                			}
                			String total="0";
                			if(json.has("total")){
                				total=json.getString("total");
                			}
                			eventBus.post(new Event.SearchAllCompleteEvent(listContent, storeId, total));
                		} else {
                			eventBus.post(new Event.SearchAllFailEvent(storeId));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.SearchAllFailEvent(storeId));
					}
                    Log.d(TAG, storeId + ":" + json.toString());
                } else {
                	Log.e(TAG, "search all Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.SearchAllFailEvent(storeId));
                }
            }
		});
	}
	
	public void search(String accessToken, final int storeId, String keyword, int start) {
		String endpoint = Constants.SEARCH_ENDPOINT + accessToken;
		final DatabaseHelper db = new DatabaseHelper(context);
		countryCode = Utils.getStaticCountryCode(context);
		Map<String, String> params = new HashMap<String, String>();
		params.put("store_id", String.valueOf(storeId));
		params.put("keyword", keyword);
		params.put("start", String.valueOf(start));
		if (countryCode.equalsIgnoreCase("vn")) {
			params.put("client", "gamota");
		} else {
			params.put("client", GP_CLIENT);
		}
		params.put("limit", "20");
		final List<ContentItemInfo> listContent = new ArrayList<ContentItemInfo>();
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		Log.e("search","url: "+url);
                		Log.e("search","result: "+json.toString());
                		if(status){
                			Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
                			JSONArray jsonArray = json.getJSONArray("data");
                			ContentItemInfo item = null;
                			for(int i=0; i< jsonArray.length(); i++){
                				JSONObject obj = jsonArray.getJSONObject(i);
                				item = gson.fromJson(obj.toString(), ContentItemInfo.class);
                				item.setPackageName(obj.getString("bundle_id"));
                				item.setPrice(obj.getInt("price"));
                				item.setPrice2(obj.getInt("price_2"));
                				if(obj.has("bought")){
                					item.setBought(obj.getInt("bought"));
                				}
                				if(obj.has("has_promotion")){
                					item.setHasPromotion(obj.getInt("has_promotion"));
                				}
                				if(db.checkAppInstalled(item.getPackageName())){
                					item.setInstalled(true);
                				} else {
                					item.setInstalled(false);
                				}
                				listContent.add(item);
                			}
                			eventBus.post(new Event.SearchCompleteEvent(listContent, storeId));
                		} else {
                			eventBus.post(new Event.SearchFailEvent(storeId));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.SearchFailEvent(storeId));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "search Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.SearchFailEvent(storeId));
                }
            }
		});
	}

	public void getItemsByCatId(String accessToken, String catId, String start) {
		String endpoint = Constants.APPLICATION_ENDPOINT + accessToken;
		countryCode = Utils.getStaticCountryCode(context);
		Map<String, String> params = new HashMap<String, String>();
		params.put("category", catId);
		params.put("start", start);
		if (countryCode.equalsIgnoreCase("vn")) {
			params.put("client", CLIENT_TYPE);
		} else {
			params.put("client", GP_CLIENT);
		}
		if (Utils.isTablet(context)) {
			params.put("filter", "has_tablet");
		} else {
			params.put("filter", "no_tablet");
		}
		final List<ContentItemInfo> listContent = new ArrayList<ContentItemInfo>();
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			Gson gson = new Gson();
                			JSONArray jsonArray = json.getJSONArray("data");
                			ContentItemInfo item = null;
                			for(int i=0; i< jsonArray.length(); i++){
                				JSONObject obj = jsonArray.getJSONObject(i);
                				item = gson.fromJson(obj.toString(), ContentItemInfo.class);
                				listContent.add(item);
                			}
                			eventBus.post(new Event.GetItemByCatSucessEvent(listContent));
                		} else {
                			eventBus.post(new Event.RequestFailEvent(json.getInt("error_code")));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "get Items by Card id Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}

	public void getHotByCatId(final String topType, String accessToken, int storeId, int categoryId, int start) {
		final DatabaseHelper db = new DatabaseHelper(context);
		String endpoint = Constants.HOT_ENDPOINT + accessToken;
		countryCode = Utils.getStaticCountryCode(context);
		Map<String, String> params = new HashMap<String, String>();
		params.put("store", String.valueOf(storeId));
		params.put("category", String.valueOf(categoryId));
		params.put("start", String.valueOf(start));
		params.put("limit", "20");
		if (countryCode.equalsIgnoreCase("vn")) {
			params.put("client", CLIENT_TYPE);
		} else {
			params.put("client", GP_CLIENT);
		}
		final List<ContentItemInfo> listContent = new ArrayList<ContentItemInfo>();
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
                			JSONArray jsonArray = json.getJSONArray("data");
                			ContentItemInfo item = null;
                			for(int i=0; i< jsonArray.length(); i++){
                				JSONObject obj = jsonArray.getJSONObject(i);
                				item = gson.fromJson(obj.toString(), ContentItemInfo.class);
                				if(obj.has("has_promotion")){
                					item.setHasPromotion(obj.getInt("has_promotion"));
                				}
                				if(obj.has("bought")){
                					item.setBought(obj.getInt("bought"));
                				}
                				if(obj.has("is_bought")){
                					item.setBought(obj.getInt("is_bought"));
                				}
                				if(db.checkAppInstalled(item.getPackageName())){
                					item.setInstalled(true);
                				} else {
                					item.setInstalled(false);
                				}
                				listContent.add(item);
                			}
                			eventBus.post(new Event.TopContentSuccessEvent(listContent, topType));
                		} else {
                			eventBus.post(new Event.RequestFailEvent(json.getInt("error_code")));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "get Hot by Catid Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void getVersionList(String accessToken, String slug, final String topType){
		String endpoint = Constants.DETAILS_ENDPOINT + accessToken;
		countryCode = Utils.getStaticCountryCode(context);
		Map<String, String> params = new HashMap<String, String>();
		params.put("application", slug);
		if (countryCode.equalsIgnoreCase("vn")) {
			params.put("client", CLIENT_TYPE);
		} else {
			params.put("client", GP_CLIENT);
		}
		params.put("version_list", "1");
		params.put("referer", "direct");
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			JSONObject obj = json.getJSONObject("data");
            				List<Version> versionList = new ArrayList<Version>();
            				JSONArray versionArr = obj.getJSONArray("versions");
            				Version v;
            				for (int m = 0; m < versionArr.length(); m++) {
            					JSONObject jo = versionArr.getJSONObject(m);
            					String versionName = jo.getString("name");
            					String changeLog = jo.getString("change_log");
            					int price1 = jo.getInt("price");
            					int price_2 = jo.getInt("price_2");
            					int id = jo.getInt("id");
            					String size = jo.getString("size");
            					v = new Version(versionName, changeLog, id, size);
            					v.setPrice1(price1);
            					v.setPrice2(price_2);
            					versionList.add(v);
            				}
                			eventBus.post(new Event.GetVersionListSuccessEvent(versionList, topType));
                		} else {
                			eventBus.post(new Event.RequestFailEvent(json.getInt("error_code")));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "get version list Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}

	public void getFullItemInfo(String accessToken, String slug, String packageName, String referer) {
		String endpoint = Constants.DETAILS_ENDPOINT + accessToken;
		countryCode = Utils.getStaticCountryCode(context);
		Map<String, String> params = new HashMap<String, String>();
		if(TextUtils.isEmpty(packageName)){
			params.put("application", slug);
		} else {
			params.put("bundle_id", packageName);
			params.put("store", Constants.ANDROID_STORE);
		}
		if (countryCode.equalsIgnoreCase("vn")) {
			params.put("client", CLIENT_TYPE);
		} else {
			params.put("client", GP_CLIENT);
		}
		params.put("version_list", "1");
		params.put("referer", referer);
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			JSONObject obj = json.getJSONObject("data");
            				String applicationId = obj.getString("application_id");
            				String type = obj.getString("application_type");
            				String title = obj.getString("title");
            				String author = obj.getString("author");
            				String packageName = obj.getString("identifier_bundle");
            				String description = obj.getString("description");
            				int totalViews = obj.getInt("total_view");
            				int totalComments = obj.getInt("total_comment");
            				int price = obj.getInt("price");
            				int price2 = obj.getInt("price_2");
            				int totalRates = obj.getInt("total_rate");
            				String avatarUrl = obj.getString("avatar");
            				int sumRates = obj.getInt("sum_rate");
            				String tag = obj.getString("tags");
            				long appstorevnId = obj.getLong("appstorevn_id");
            				String permissions = obj.getString("permission");
            				String videoLink = obj.getString("video_link");
            				String gpLink = obj.getString("root_link");
            
            				List<Version> versionList = new ArrayList<Version>();
            				List<String> screenShots = new ArrayList<String>();
            
            				JSONArray screenShotsArray = obj.getJSONArray("images");
            				for (int j = 0; j < screenShotsArray.length(); j++) {
            					JSONObject jo = screenShotsArray.getJSONObject(j);
            					String imageUrl = jo.getString("path_save");
            					screenShots.add(imageUrl);
            				}
            
            				JSONArray versionArr = obj.getJSONArray("versions");
            				Version v;
            				for (int m = 0; m < versionArr.length(); m++) {
            					JSONObject jo = versionArr.getJSONObject(m);
            					String versionName = jo.getString("name");
            					String changeLog = jo.getString("change_log");
            					int price1 = jo.getInt("price");
            					int price_2 = jo.getInt("price_2");
            					int id = jo.getInt("id");
            					String size = jo.getString("size");
            					v = new Version(versionName, changeLog, id, size);
            					v.setPrice1(price1);
            					v.setPrice2(price_2);
            					versionList.add(v);
            				}
            
            				JSONObject verObj = obj.getJSONObject("version");
            				String version = verObj.getString("name");
            				String changeLog = verObj.getString("change_log");
            				String published = verObj.getString("published");
            				int updateFree = verObj.getInt("update_free");
            				String size = verObj.getString("size");
            
            				JSONArray relatedArray = obj.getJSONArray("related_applications");
            				List<RelatedItem> relatedAppList = new ArrayList<RelatedItem>();
            				RelatedItem relatedApp;
            				for (int j = 0; j < relatedArray.length(); j++) {
            					JSONObject relatedObj = relatedArray.getJSONObject(j);
            					String slug = relatedObj.getString("application_id");
            					String name = relatedObj.getString("title");
            					String avt = relatedObj.getString("avatar");
            					String rAuthor = relatedObj.getString("author");
            
            					relatedApp = new RelatedItem();
            					relatedApp.setAuthor(rAuthor);
            					relatedApp.setIconUrl(avt);
            					relatedApp.setName(name);
            					relatedApp.setSlug(slug);
            					relatedAppList.add(relatedApp);
            				}
            				ContentItemInfo item = new ContentItemInfo();
            				if(obj.has("has_promotion")){
            					item.setHasPromotion(obj.getInt("has_promotion"));
            				}
            				item.setAuthor(author);
            				item.setAvatar(avatarUrl);
            				item.setApplicationId(applicationId);
            				item.setChangeLog(changeLog);
            				item.setDescription(description);
            				item.setPublished(published);
            				item.setScreenShots(screenShots);
            				item.setVideoLink(videoLink);
            				item.setSize(size);
            				item.setPackageName(packageName);
            				item.setTag(tag);
            				item.setType(type);
            				item.setTitle(title);
            				item.setUpdateFree(updateFree);
            				item.setVersion(version);
            				item.setPrice(price);
            				item.setPrice2(price2);
            				item.setGiftbox(obj.getInt("giftbox"));
            				item.setGiftboxDaysToGet(obj.getInt("giftbox_days_to_get"));
            				if(obj.has("install_attach_application")){
            					item.setInstallAttachApplication(obj.getInt("install_attach_application"));
            				}
            				if(obj.has("attach_application_slug")){
            					item.setAttachApplicationSlug(obj.getString("attach_application_slug"));
            				}
            				if(obj.has("attach_application_avatar")){
            					item.setAttachApplicationAvatar(obj.getString("attach_application_avatar"));
            				}
            				if(obj.has("attach_application_title")){
            					item.setAttachApplicationTitle(obj.getString("attach_application_title"));
            				}
            				item.setTotalComments(totalComments);
            				item.setTotalViews(totalViews);
            				item.setRelatedItems(relatedAppList);
            				item.setVersionList(versionList);
            				item.setAppstorevnId(appstorevnId);
            				item.setPermissions(permissions);
            				item.setGpLink(gpLink);
            				if(obj.has("is_bought")){
            					item.setBought(obj.getInt("is_bought"));
            				}
            				if (totalRates == 0) {
            					item.setRating(0);
            				} else {
            					item.setRating(sumRates / totalRates);
            				}
                			eventBus.post(new Event.GetFullItemInfoSuccessEvent(item));
                		} else {
                			eventBus.post(new Event.GetFullItemInfoFail(json.getString("message")));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "get full Item info Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}

	public void getComments(String accessToken, String appId, int start) {
		String endpoint = Constants.COMMENTS_ENDPOINT + accessToken;
		countryCode = Utils.getStaticCountryCode(context);
		Map<String, String> params = new HashMap<String, String>();
		params.put("application", appId);
		params.put("start", String.valueOf(start));
		if (countryCode.equalsIgnoreCase("vn")) {
			params.put("client", CLIENT_TYPE);
		} else {
			params.put("client", GP_CLIENT);
		}
		final List<CommentItem> listComment = new ArrayList<CommentItem>();
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	Log.e("getComm", url+json.toString());
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
                			JSONArray jsonArray = json.getJSONArray("data");
                			CommentItem item = null;
                			for(int i=0; i< jsonArray.length(); i++){
                				JSONObject obj = jsonArray.getJSONObject(i);
                				item = gson.fromJson(obj.toString(), CommentItem.class);
                				listComment.add(item);
                			}
                			eventBus.post(new Event.GetCommentSuccessEvent(listComment));
                		} else {
                			eventBus.post(new Event.GetCommentsFailEvent(json.getString("message")));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "get comments Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void buyAttached(final String topType, String accessToken, final String appId, final int versionId) {
		String endpoint = Constants.BUY_ENDPOINT + accessToken;
		countryCode = Utils.getStaticCountryCode(context);
		Map<String, String> params = new HashMap<String, String>();
		params.put("application", appId);
		params.put("version", String.valueOf(versionId));
		if (countryCode.equalsIgnoreCase("vn")) {
			params.put("client", CLIENT_TYPE);
		} else {
			params.put("client", GP_CLIENT);
		}
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			eventBus.post(new Event.BuyAttachedSuccessEvent(appId, versionId, topType));
                		} else {
                			eventBus.post(new Event.BuyFailEvent(json.getString("message"), topType));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "buy attached Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}

	public void buy(final String topType, String accessToken, final String appId, final long versionId) {
		String endpoint = Constants.BUY_ENDPOINT + accessToken;
		countryCode = Utils.getStaticCountryCode(context);
		Map<String, String> params = new HashMap<String, String>();
		params.put("application", appId);
		params.put("version", String.valueOf(versionId));
		if (countryCode.equalsIgnoreCase("vn")) {
			params.put("client", CLIENT_TYPE);
		} else {
			params.put("client", GP_CLIENT);
		}
		// if(!c.getSharedPreferences(Constants.PREF_DEALER_KEY,
		// 0).getString(Constants.DEALER_KEY, "").equals("")){
		// params.put("device_id", androidID);
		// params.put("key", dealerKey);
		// }
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			eventBus.post(new Event.BuySuccessEvent(appId, versionId, topType));
                		} else {
                			eventBus.post(new Event.BuyFailEvent(json.getString("message"), topType));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "buy Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void buyMultiple(String accessToken, final List<AppStoreVnApplicationInfo> appIdList){
		final List<AppStoreVnApplicationInfo> buySuccessList = new ArrayList<AppStoreVnApplicationInfo>();
		String endpoint = Constants.BUY_ENDPOINT + accessToken;
		countryCode = Utils.getStaticCountryCode(context);
		Map<String, String> params;
		String value;
		int count = 0;
		for(final AppStoreVnApplicationInfo app : appIdList){
			params = new HashMap<String, String>();
			params.put("application", app.getSlug());
			params.put("version", "0");
			if (countryCode.equalsIgnoreCase("vn")) {
				params.put("client", CLIENT_TYPE);
			} else {
				params.put("client", GP_CLIENT);
			}
			try {
				value = post(endpoint, params);
				count++;
				JSONObject jsonObject = new JSONObject(value);
				boolean status = jsonObject.getBoolean("status");
				if(status){
					buySuccessList.add(app);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			catch (JSONException e) {
				e.printStackTrace();
			}
		}
		if(count == appIdList.size()){
			eventBus.post(new Event.BuyMultipleSuccessEvent(buySuccessList));
		}
	}
	
	public void buyMultipleContent(String accessToken, final List<ContentItemInfo> appIdList){
		final List<ContentItemInfo> buySuccessList = new ArrayList<ContentItemInfo>();
		String endpoint = Constants.BUY_ENDPOINT + accessToken;
		countryCode = Utils.getStaticCountryCode(context);
		Map<String, String> params;
		String value;
		int count = 0;
		System.out.println(appIdList.size() + " asjfsdkaghfaslgfasjdfjkasdhjk");
		for(final ContentItemInfo app : appIdList){
			params = new HashMap<String, String>();
			params.put("application", app.getApplicationId());
			params.put("version", "0");
			if (countryCode.equalsIgnoreCase("vn")) {
				params.put("client", CLIENT_TYPE);
			} else {
				params.put("client", GP_CLIENT);
			}
			try {
				value = post(endpoint, params);
				System.out.println(value);
				count++;
				JSONObject jsonObject = new JSONObject(value);
				boolean status = jsonObject.getBoolean("status");
				if(status){
					buySuccessList.add(app);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			catch (JSONException e) {
				e.printStackTrace();
			}
		}
		if(count == appIdList.size()){
			eventBus.post(new Event.BuyMultipleContentSuccessEvent(buySuccessList));
		}
	}
	
	public void getMultipleDownloadLink(String accessToken, List<AppStoreVnApplicationInfo> appIdList, boolean isRooted, String referer){
		String endpoint = Constants.DOWNLOAD_ENDPOINT + accessToken;
		Map<String, String> params;
		final List<DownloadLink> downloadLinkList = new ArrayList<DownloadLink>();
		String value;
		int count = 0;
		for(AppStoreVnApplicationInfo app : appIdList){
			params = new HashMap<String, String>();
			params.put("application", app.getSlug());
			if (countryCode.equalsIgnoreCase("vn")) {
				params.put("client", CLIENT_TYPE);
			} else {
				params.put("client", GP_CLIENT);
			}
			params.put("version", "0");
			params.put("device_id", Utils.getDeviceId(context));
			params.put("referer", referer);
			if (isRooted) {
				params.put("machine_status", "1");
			} else {
				params.put("machine_status", "0");
			}
			try {
				List<String> extraUrls = new ArrayList<String>();
				value = post(endpoint, params);
				System.out.println(value);
				count++;
				JSONObject json = new JSONObject(value);
				boolean status = json.getBoolean("status");
        		if(status){
        			JSONObject obj = json.getJSONObject("data");
        			String downloadLink = obj.getString("download");
        			String type = obj.getString("type");
        			JSONArray extras = obj.getJSONArray("extras");
        			String extraDownloadLink = "";
        			if(extras.length() > 0){
        				for(int i=0; i<extras.length(); i++){
        					JSONObject extrasObj = extras.getJSONObject(i);
            				extraDownloadLink = extrasObj.getString("download");
            				extraUrls.add(extraDownloadLink);
        				}
        			}
        			DownloadLink download = new DownloadLink();
        			download.setDownload(downloadLink);
        			download.setExtraDownload(extraUrls);
        			download.setType(type);
        			download.setTitle(app.getName());
        			download.setAvatar(app.getAvatar());
        			download.setPackageName(app.getPackageName());
        			downloadLinkList.add(download);
        		}
			} catch (IOException e) {
				e.printStackTrace();
			}
			catch (JSONException e) {
				e.printStackTrace();
			}
		}
		if(count == appIdList.size()){
			eventBus.post(new Event.GetMultipleDownloadLinkSucessEvent(downloadLinkList));
		}
	}
	
	public void getMultipleContentDownloadLink(String accessToken, List<ContentItemInfo> appIdList, boolean isRooted, String referer){
		String endpoint = Constants.DOWNLOAD_ENDPOINT + accessToken;
		Map<String, String> params;
		final List<DownloadLink> downloadLinkList = new ArrayList<DownloadLink>();
		String value;
		int count = 0;
		for(ContentItemInfo app : appIdList){
			params = new HashMap<String, String>();
			params.put("application", app.getApplicationId());
			if (countryCode.equalsIgnoreCase("vn")) {
				params.put("client", CLIENT_TYPE);
			} else {
				params.put("client", GP_CLIENT);
			}
			params.put("version", "0");
			params.put("device_id", Utils.getDeviceId(context));
			params.put("referer", referer);
			if (isRooted) {
				params.put("machine_status", "1");
			} else {
				params.put("machine_status", "0");
			}
			try {
				List<String> extraUrls = new ArrayList<String>();
				value = post(endpoint, params);
				count++;
				JSONObject json = new JSONObject(value);
				boolean status = json.getBoolean("status");
        		if(status){
        			JSONObject obj = json.getJSONObject("data");
        			String downloadLink = obj.getString("download");
        			String type = obj.getString("type");
        			JSONArray extras = obj.getJSONArray("extras");
        			String extraDownloadLink = "";
        			if(extras.length() > 0){
        				for(int i=0; i<extras.length(); i++){
        					JSONObject extrasObj = extras.getJSONObject(i);
            				extraDownloadLink = extrasObj.getString("download");
            				extraUrls.add(extraDownloadLink);
        				}
        			}
        			DownloadLink download = new DownloadLink();
        			download.setDownload(downloadLink);
        			download.setExtraDownload(extraUrls);
        			download.setType(type);
        			download.setTitle(app.getTitle());
        			download.setAvatar(app.getAvatar());
        			download.setPackageName(app.getPackageName());
        			downloadLinkList.add(download);
        		}
			} catch (IOException e) {
				e.printStackTrace();
			}
			catch (JSONException e) {
				e.printStackTrace();
			}
		}
		if(count == appIdList.size()){
			eventBus.post(new Event.GetMultipleDownloadLinkSucessEvent(downloadLinkList));
		}
	}

	public void getDownloadLink(final String topType, String accessToken, final String appId, long versionId, boolean isRooted, String referer, boolean isMovie) {
		String endpoint = Constants.DOWNLOAD_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		if (versionId == 0) {
			params.put("application", appId);
			if (countryCode.equalsIgnoreCase("vn")) {
				params.put("client", CLIENT_TYPE);
			} else {
				params.put("client", GP_CLIENT);
			}
		} else {
			params.put("application", appId);
			params.put("version", String.valueOf(versionId));
			if (countryCode.equalsIgnoreCase("vn")) {
				params.put("client", CLIENT_TYPE);
			} else {
				params.put("client", GP_CLIENT);
			}
		}
		if(isMovie){
			params.put("content", "film");
		}
		params.put("device_id", Utils.getDeviceId(context));
		params.put("referer", referer);
		if (isRooted) {
			params.put("machine_status", "1");
		} else {
			params.put("machine_status", "0");
		}
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	Log.e("getDownload","getDownload: "+json.toString());
                	try {
                		List<String> extraUrls = new ArrayList<String>();
                		boolean status = json.getBoolean("status");
                		if(status){
                			JSONObject obj = json.getJSONObject("data");
                			String downloadLink = obj.getString("download");
                			String type = obj.getString("type");
                			JSONArray extras = obj.getJSONArray("extras");
                			String extraDownloadLink = "";
                			if(extras.length() > 0){
                				for(int i=0; i<extras.length(); i++){
                					JSONObject extrasObj = extras.getJSONObject(i);
                    				extraDownloadLink = extrasObj.getString("download");
                    				extraUrls.add(extraDownloadLink);
                				}
                			}
                			DownloadLink download = new DownloadLink();
                			download.setDownload(downloadLink);
                			download.setExtraDownload(extraUrls);
                			download.setType(type);
                			eventBus.post(new Event.GetDownloadLinkSuccess(download, topType, appId));
                		} else {
                			eventBus.post(new Event.GetDownloadLinkFailEvent(json.getString("message"), topType));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "get download link Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void getAttchedDownloadLink(final String topType, String accessToken, String appId, long versionId, boolean isRooted, String referer, boolean isMovie) {
		String endpoint = Constants.DOWNLOAD_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		if (versionId == 0) {
			params.put("application", appId);
			if (countryCode.equalsIgnoreCase("vn")) {
				params.put("client", CLIENT_TYPE);
			} else {
				params.put("client", GP_CLIENT);
			}
		} else {
			params.put("application", appId);
			params.put("version", String.valueOf(versionId));
			if (countryCode.equalsIgnoreCase("vn")) {
				params.put("client", CLIENT_TYPE);
			} else {
				params.put("client", GP_CLIENT);
			}
		}
		if(isMovie){
			params.put("content", "film");
		}
		params.put("device_id", Utils.getDeviceId(context));
		params.put("referer", referer);
		if (isRooted) {
			params.put("machine_status", "1");
		} else {
			params.put("machine_status", "0");
		}
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		List<String> extraUrls = new ArrayList<String>();
                		boolean status = json.getBoolean("status");
                		if(status){
                			JSONObject obj = json.getJSONObject("data");
                			String downloadLink = obj.getString("download");
                			String type = obj.getString("type");
                			JSONArray extras = obj.getJSONArray("extras");
                			String extraDownloadLink = "";
                			if(extras.length() > 0){
                				for(int i=0; i<extras.length(); i++){
                					JSONObject extrasObj = extras.getJSONObject(i);
                    				extraDownloadLink = extrasObj.getString("download");
                    				extraUrls.add(extraDownloadLink);
                				}
                			}
                			DownloadLink download = new DownloadLink();
                			download.setDownload(downloadLink);
                			download.setExtraDownload(extraUrls);
                			download.setType(type);
                			eventBus.post(new Event.GetAttachedDownloadLinkSuccess(download, topType));
                		} else {
                			eventBus.post(new Event.GetAttachedDownloadLinkFailEvent(json.getString("message"), topType));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "get attached download link Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}

	public void writeComment(String accessToken, String appId, String comment) {
		String endpoint = Constants.WRITE_COMMENT_ENDPOINT + accessToken;
		countryCode = Utils.getStaticCountryCode(context);
		Map<String, String> params = new HashMap<String, String>();
		params.put("application", appId);
		params.put("content", comment);
		if (countryCode.equalsIgnoreCase("vn")) {
			params.put("client", CLIENT_TYPE);
		} else {
			params.put("client", GP_CLIENT);
		}
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			eventBus.post(new Event.PostCommentSuccessEvent());
                		} else {
                			eventBus.post(new Event.RequestFailEvent(json.getInt("error_code")));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "write comment Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}

	public void rate(String accessToken, String appId, float score) {
		String endpoint = Constants.RATING_ENDPOINT + accessToken;
		countryCode = Utils.getStaticCountryCode(context);
		Map<String, String> params = new HashMap<String, String>();
		params.put("application", appId);
		params.put("rate", String.valueOf(score));
		if (countryCode.equalsIgnoreCase("vn")) {
			params.put("client", CLIENT_TYPE);
		} else {
			params.put("client", GP_CLIENT);
		}
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			eventBus.post(new Event.RatingSuccessEvent());
                		} else {
                			eventBus.post(new Event.RequestFailEvent(json.getInt("error_code")));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "rate Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}

	public void giftcode(String userName, String giftCode) {
		String hash = Utils.generateHashMD5(giftCode + userName + HASH_KEY);
		String endpoint = Constants.GIFTCODE_ENDPOINT + userName + "/" + giftCode + "/" + hash;
		aq.ajax(endpoint, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
        					String message = json.getString("msg");
        					eventBus.post(new Event.GiftCodeEvent(message, true));
        				} else {
        					String message = json.getString("msg");
        					eventBus.post(new Event.GiftCodeEvent(message, false));
        				}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "gift code Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}

//	public String getDirectLink(String url) {
//		Map<String, String> params = new HashMap<String, String>();
//		long backoff = BACKOFF_MILLI_SECONDS + new Random().nextInt(1000);
//		String value = "";
//		String directLink = "";
//		for (int i = 1; i <= MAX_ATTEMPTS; i++) {
//			Log.d(TAG, "Attempt #" + i + " to connect");
//			try {
//				value = unsecurePost(url, params);
//				String s = value.substring(value.indexOf("<a"), value.indexOf("'>"));
//				directLink = s.substring(9, s.length());
//				return directLink;
//			} catch (IOException e) {
//				Log.e(TAG, "Failed to register on attempt " + i + ":" + e);
//				if (i == MAX_ATTEMPTS) {
//					break;
//				}
//				try {
//					Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
//					Thread.sleep(backoff);
//				} catch (InterruptedException e1) {
//					// Activity finished before we complete - exit.
//					Log.d(TAG, "Thread interrupted: abort remaining retries!");
//					Thread.currentThread().interrupt();
//					directLink = "timeout";
//					return directLink;
//				}
//				backoff *= 2;
//			}
//		}
//		return directLink;
//	}

	public void checkContentUpdate(String accessToken, String type, int start, int limit, String store, String packageNameList,final boolean show) {
		String endpoint = Constants.UPDATE_ENDPOINT + accessToken;
		countryCode = Utils.getStaticCountryCode(context);
		Map<String, String> params = new HashMap<String, String>();
		params.put("start", String.valueOf(start));
		params.put("limit", String.valueOf(limit));
		params.put("store", store);
		if (countryCode.equalsIgnoreCase("vn")) {
			params.put("client", CLIENT_TYPE);
		} else {
			params.put("client", GP_CLIENT);
		}
		if(type.equalsIgnoreCase("apps")){
			params.put("bundle_id", packageNameList);
		} else {
			params.put("content_id", packageNameList);
		}
		params.put("uid", Utils.getDeviceId(context));
		final List<AppStoreVnApplicationInfo> updateList = new ArrayList<AppStoreVnApplicationInfo>();
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
                			AppStoreVnApplicationInfo ai;
                			JSONArray arr = json.getJSONArray("data");
                			if(arr.length() == 0){
                				eventBus.post(new Event.NoUpdateContentEvent());
                				return;
                			}
                			for(int i=0; i<arr.length();i++){
                				JSONObject obj = arr.getJSONObject(i);
                				ai = gson.fromJson(obj.toString(), AppStoreVnApplicationInfo.class);
                				updateList.add(ai);
                			}
        					eventBus.post(new Event.HasUpdateContentEvent(updateList, show));
        				} else {
        					eventBus.post(new Event.NoUpdateContentEvent());
        				}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "check content update Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}

//	public List<ContentItem> checkContentUpdate(String accessToken, int start,
//			int limit, String store, String packageNameList, String androidID) {
//		String endpoint = Constants.UPDATE_ENDPOINT + accessToken;
//		countryCode = Utils.getStaticCountryCode(context);
//		Map<String, String> params = new HashMap<String, String>();
//		params.put("start", String.valueOf(start));
//		params.put("limit", String.valueOf(limit));
//		params.put("store", store);
//		if (countryCode.equalsIgnoreCase("us")) {
//			params.put("client", GP_CLIENT);
//		} else {
//			params.put("client", CLIENT_TYPE);
//		}
//		params.put("content_id", packageNameList);
//		params.put("uid", androidID);
//		long backoff = BACKOFF_MILLI_SECONDS + new Random().nextInt(1000);
//		String value = "";
//		List<ContentItem> updateList = new ArrayList<ContentItem>();
//		ContentItem item;
//		for (int i = 1; i <= MAX_ATTEMPTS; i++) {
//			Log.d(TAG, "Attempt #" + i + " to connect");
//			try {
//				value = post(endpoint, params);
//				// .println("updates: " + value);
//				JSONObject obj = new JSONObject(value);
//				JSONArray arr = obj.getJSONArray("data");
//				for (int j = 0; j < arr.length(); j++) {
//					JSONObject data = arr.getJSONObject(j);
//					String appId = data.getString("application_id");
//					String newVersion = data.getString("version");
//					String name = data.getString("title");
//					item = new ContentItem();
//					item.setNewVersion(newVersion);
//					item.setSlug(appId);
//					item.setFileName(name);
//					item.setType(store);
//					updateList.add(item);
//				}
//				return updateList;
//			} catch (IOException e) {
//				Log.e(TAG, "Failed to register on attempt " + i + ":" + e);
//				if (i == MAX_ATTEMPTS) {
//					break;
//				}
//				try {
//					Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
//					Thread.sleep(backoff);
//				} catch (InterruptedException e1) {
//					// Activity finished before we complete - exit.
//					Log.d(TAG, "Thread interrupted: abort remaining retries!");
//					Thread.currentThread().interrupt();
//					return null;
//				}
//				// increase backoff exponentially
//				backoff *= 2;
//			} catch (JSONException e) {
//				e.printStackTrace();
//				return updateList;
//			}
//		}
//		return updateList;
//	}

	public void registerDevice(final Context context, String accessToken, final String regId, String allowPush, boolean isRooted, int lastNotificationId)
			throws NameNotFoundException {
		String carrier = Utils.getCarrier(context);
		String phomeNumber = Utils.getPhone(context);
		String serverUrl = SERVER_URL + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("client", "android");
		params.put("client_version","Gamota_Android_v"+ context.getPackageManager().getPackageInfo("com.gamota.mobi", 0).versionName);
		params.put("device_token", regId);
		params.put("device_id", Utils.getDeviceId(context));
		params.put("imei", Utils.getDeviceId(context));
		params.put("device_os", deviceOSName);
		params.put("device_os_version", deviceOSVersion);
		params.put("vendor", carrier);
		params.put("phone_number", phomeNumber);
		params.put("allow_push", allowPush);
		params.put("last_notification_id", String.valueOf(lastNotificationId));
		if(isRooted){
			params.put("jb", "1");
		} else {
			params.put("jb", "0");
		}
		long backoff = BACKOFF_MILLI_SECONDS + new Random().nextInt(1000);
		  for (int i = 1; i <= MAX_ATTEMPTS; i++) {
			   Log.d(TAG, "Attempt #" + i + " to register");
			   try {
				    post(serverUrl, params);
				    //GCMRegistrar.setRegisteredOnServer(context, true);
				    return;
			   } catch (IOException e) {
				    Log.e(TAG, "Failed to register on attempt " + i + ":" + e);
				    if (i == MAX_ATTEMPTS) {
				    	break;
				    }
				    try {
				     Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
				     Thread.sleep(backoff);
				    } catch (InterruptedException e1) {
				     // Activity finished before we complete - exit.
				     Log.d(TAG, "Thread interrupted: abort remaining retries!");
				     Thread.currentThread().interrupt();
				     return;
				    }
				    // increase backoff exponentially
				    backoff *= 2;
			   }
		  }
	}

	/**
	 * Unregister this account/device pair within the server.
	 */
	public void unregister(final Context context, final String regId) {
		Log.i(TAG, "unregistering device (regId = " + regId + ")");
		String serverUrl = SERVER_URL + "/unregister";
		Map<String, String> params = new HashMap<String, String>();
		params.put("regId", regId);
		aq.ajax(serverUrl, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                    GCMRegistrar.setRegisteredOnServer(context, false);
                } else {
                	Log.e(TAG, "unregister Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}

	public void changePassword(String accessToken, String oldPassword, String newPassword) {
		String endpoint = Constants.CHANGE_PASS_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("old_password", oldPassword);
		params.put("new_password", newPassword);
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		String message = json.getString("message");
                		if(status){
                			eventBus.post(new Event.ChangePasswordSuccessEvent(message));
                		} else {
                			eventBus.post(new Event.ChangePasswordFailEvent(message));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "change password Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}

	public void checkAppStoreVnUpdate(String client, String deviceId, String version, String build, String isRooted) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("client", client);
		params.put("device_id", deviceId);
		params.put("version", version);
		params.put("build", build);
		params.put("machine_status", isRooted);
		String endpoint = Constants.CHECK_UPDATE_ENDPOINT;
		final AppStoreVnUpdateData updateData = new AppStoreVnUpdateData();
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	System.err.println("update: " + json.toString());
                	try {
                		boolean status = json.getBoolean("status");
                		JSONObject data = json.getJSONObject("data");
                		String countryCode = data.getString("country_code");
                		if(!countryCode.equalsIgnoreCase("vn")){
                			countryCode = "us";
                		}
                		updateData.setCountryCode(countryCode);
                		if (!status) {
        					updateData.setStatus(false);
        					JSONObject moreObj = json.getJSONObject("more_settings");
        					int dealer = moreObj.getInt("dealer");
        					updateData.setDealer(dealer);
        					PreferenceManager.getDefaultSharedPreferences(context).edit().putInt(ENABLE_FREE_TYM, dealer).commit();
        					eventBus.post(new Event.LatestVersionEvent(countryCode));
        				} else {
        					updateData.setStatus(true);
        					JSONObject dataObj = json.getJSONObject("data");
        					String updateURL = dataObj.getString("update_uri");
        					boolean isForce = dataObj.getBoolean("force_update");
        					JSONObject messObj = dataObj.getJSONObject("message");
        					String title = messObj.getString("title");
        					String content = messObj.getString("message");
        					JSONObject moreObj = json.getJSONObject("more_settings");
        					int dealer = moreObj.getInt("dealer");
        					PreferenceManager.getDefaultSharedPreferences(context).edit().putInt(ENABLE_FREE_TYM, dealer).commit();
        					updateData.setDealer(dealer);
        					updateData.setForce(isForce);
        					updateData.setMessContent(content);
        					updateData.setMessTitle(title);
        					updateData.setUpdateUrl(updateURL);
        					eventBus.post(updateData);
        				}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "check appstore vn update Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}

	public void checkVersionBought(final String type, String accessToken, final View v, final MenuItem item){
		Map<String, String> params = new HashMap<String, String>();
		params.put("version_id", String.valueOf(item.getItemId()));
		String endpoint = Constants.CHECK_VERSION_BOUGHT_ENDPOINT + accessToken;
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			JSONObject obj = json.getJSONObject("data");
                			int isBought = obj.getInt("is_bought");
                			if(isBought == 1){
                				eventBus.post(new Event.VersionBoughtEvent(v, item, type));
                			} else {
                				eventBus.post(new Event.VersionNotBoughtEvent(v, item, type));
                			}
                		} else {
                			eventBus.post(new Event.CheckVersionBoughtFail(json.getString("message")));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, "Check version bought: " + json.toString());
                } else {
                	Log.e(TAG, "check version bought Error: " + ajaxStatus.getCode());
                	//eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void registerFacebook(String accessToken, String facebookToken, String username, String password) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("facebook_access_token", facebookToken);
		params.put("username", username);
		params.put("password", password);
		params.put("device_id", Utils.getDeviceId(context));
		params.put("device_os", deviceOSName);
		params.put("device_os_version", deviceOSVersion);
		String endpoint = Constants.FB_REGISTER_ENDPOINT + accessToken;
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
                			AccessToken accessToken = gson.fromJson(json.getJSONObject("data").toString(), AccessToken.class);
                			eventBus.post(new Event.RegisterFacebookSuccessEvent(accessToken));
                		} else {
                			eventBus.post(new Event.RegisterFailedEvent(json.getString("message")));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "register facebook Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void registerGoogle(String accessToken, String googleToken, String username, String password) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("google_access_token", googleToken);
		params.put("username", username);
		params.put("password", password);
		params.put("device_id", Utils.getDeviceId(context));
		params.put("device_os", deviceOSName);
		params.put("device_os_version", deviceOSVersion);
		String serverUrl = Constants.REGISTER_GOOGLE_ENDPOINT + accessToken;
		aq.ajax(serverUrl, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
                			AccessToken accessToken = gson.fromJson(json.getJSONObject("data").toString(), AccessToken.class);
                			eventBus.post(new Event.RegisterGoogleSuccessEvent(accessToken));
                		} else {
                			eventBus.post(new Event.RegisterFailedEvent(json.getString("message")));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "register google Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}

	public void getUserTransactions(String accessToken, int start) {
		String endpoint = Constants.TRANSACTION_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("start", String.valueOf(start));
		final List<UserTransaction> transList = new ArrayList<UserTransaction>();
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			JSONArray array = json.getJSONArray("data");
                			Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
                			UserTransaction ut;
        					for (int i = 0; i < array.length(); i++) {
        						JSONObject jo = array.getJSONObject(i);
        						ut = gson.fromJson(jo.toString(), UserTransaction.class);
        						transList.add(ut);
        					}
        					eventBus.post(new Event.UserTransactionSuccessEvent(transList));
                		} else {
                			eventBus.post(new Event.RequestFailEvent(json.getInt("error_code")));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "get user transactions Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}

	public void getHotKeywords(String accessToken, String store, String limit) {
		String endpoint = Constants.HOT_KEYWORD_ENDPOINT + accessToken;
		countryCode = Utils.getStaticCountryCode(context);
		Map<String, String> params = new HashMap<String, String>();
		params.put("store", store);
		params.put("limit", limit);
		if (countryCode.equalsIgnoreCase("vn")) {
			params.put("client", CLIENT_TYPE);
		} else {
			params.put("client", GP_CLIENT);
		}
		final List<String> listKeyword = new ArrayList<String>();
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			JSONArray array = json.getJSONArray("data");
        					for (int j = 0; j < array.length(); j++) {
        						String keyword = array.getString(j);
        						listKeyword.add(keyword);
        					}
        					eventBus.post(new Event.HotKeywordSuccessEvent(listKeyword));
                		} else {
                			eventBus.post(new Event.RequestFailEvent(json.getInt("error_code")));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "get hotkey words Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}

	public void getDownloadedList(String accessToken, final int storeId) {
		String endpoint = Constants.DOWNLOADED_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("store_id", String.valueOf(storeId));
		final List<UserDownloaded> downloadedList = new ArrayList<UserDownloaded>();
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			JSONArray array = json.getJSONArray("data");
                			UserDownloaded ud;
                			Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
        					for (int j = 0; j < array.length(); j++) {
        						JSONObject jo = array.getJSONObject(j);
        						ud = gson.fromJson(jo.toString(), UserDownloaded.class);
        						ud.setType("apps");
        						downloadedList.add(ud);
        					}
        					eventBus.post(new Event.GetUserDownloadedSuccessEvent(downloadedList, storeId));
                		} else {
                			eventBus.post(new Event.GetDownloadLogFailEvent(json.getInt("error_code"), storeId));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.GetDownloadLogFailEvent(-2, storeId));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "get downloaded list Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.GetDownloadLogFailEvent(ajaxStatus.getCode(), storeId));
                }
            }
		});
	}

	public void getRecommentItem(String accessToken, String store, String start, String limit) {
		String endpoint = Constants.RECOMMEND_ENDPOINT + accessToken;
		countryCode = Utils.getStaticCountryCode(context);
		Map<String, String> params = new HashMap<String, String>();
		params.put("store", store);
		params.put("start", start);
		params.put("limit", limit);
		if (countryCode.equalsIgnoreCase("vn")) {
			params.put("client", CLIENT_TYPE);
		} else {
			params.put("client", GP_CLIENT);
		}
		if (Utils.isTablet(context)) {
			params.put("filter", "has_tablet");
		} else {
			params.put("filter", "no_tablet");
		}
		final List<RecommendItem> recommendList = new ArrayList<RecommendItem>();
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	Log.e("getRecommendItem","getRecommendItem: "+json.toString());
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			Log.d(TAG, "recommend: " + json.toString());
                			JSONArray array = json.getJSONArray("data");
                			RecommendItem item;
                			JSONObject jo;
        					for (int j = 0; j < array.length(); j++) {
        						jo = array.getJSONObject(j);
        						item = new RecommendItem(jo.getString("application_id"), jo.getString("title"), jo.getString("avatar"), jo.getInt("total_rate"), jo.getInt("sum_rate"), jo.getInt("price"), jo.getInt("price_2"));
        						recommendList.add(item);
        					}
        					eventBus.post(new Event.GetRecommentItemSuccessEvent(recommendList));
                		} else {
                			eventBus.post(new Event.GetRecommendFailEvent(json.getInt("error_code")));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.GetRecommendFailEvent(-2));
					}
                } else {
                	Log.e(TAG, "get recommend item Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.GetRecommendFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}

	public void clickBanner(String url) {
		aq.ajax(url, JSONObject.class, new AjaxCallback<JSONObject>());
	}

//	public String gameStatus(String endpoint, String accessToken) {
//		Map<String, String> params = new HashMap<String, String>();
//		params.put("client", "android");
//		String url = endpoint + accessToken;
//		long backoff = BACKOFF_MILLI_SECONDS + new Random().nextInt(1000);
//		String value = "";
//		for (int i = 1; i <= MAX_ATTEMPTS; i++) {
//			Log.d(TAG, "Attempt #" + i + " to connect");
//			try {
//				value = post(url, params);
//				// //.println("recommend " + value);
//				return value;
//			} catch (IOException e) {
//				Log.e(TAG, "Failed to register on attempt " + i + ":" + e);
//				if (i == MAX_ATTEMPTS) {
//					break;
//				}
//				try {
//					Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
//					Thread.sleep(backoff);
//				} catch (InterruptedException e1) {
//					// Activity finished before we complete - exit.
//					Log.d(TAG, "Thread interrupted: abort remaining retries!");
//					Thread.currentThread().interrupt();
//					return value;
//				}
//				backoff *= 2;
//			}
//		}
//		return value;
//	}

//	public String gamePlay(String endpoint, String accessToken,
//			String gameToken, String val, String tymType) {
//		Map<String, String> params = new HashMap<String, String>();
//		params.put("client", "android");
//		params.put("game_token", gameToken);
//		params.put("bet", val);
//		params.put("tym", tymType);
//		long backoff = BACKOFF_MILLI_SECONDS + new Random().nextInt(1000);
//		String url = endpoint + accessToken;
//		String value = "";
//		for (int i = 1; i <= MAX_ATTEMPTS; i++) {
//			Log.d(TAG, "Attempt #" + i + " to connect");
//			try {
//				value = post(url, params);
//				// //.println("recommend " + value);
//				return value;
//			} catch (IOException e) {
//				Log.e(TAG, "Failed to register on attempt " + i + ":" + e);
//				if (i == MAX_ATTEMPTS) {
//					break;
//				}
//				try {
//					Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
//					Thread.sleep(backoff);
//				} catch (InterruptedException e1) {
//					// Activity finished before we complete - exit.
//					Log.d(TAG, "Thread interrupted: abort remaining retries!");
//					Thread.currentThread().interrupt();
//					return value;
//				}
//				backoff *= 2;
//			}
//		}
//		return value;
//	}

	public UserInfo callGoogleApi(String googleToken) throws IOException, InterruptedException {
		String str = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + googleToken;
		URL url;
		url = new URL(str);
		UserInfo user = null;
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		int serverCode = con.getResponseCode();
		long backoff = BACKOFF_MILLI_SECONDS + new Random().nextInt(1000);
		String value = "";
		for (int i = 1; i <= MAX_ATTEMPTS; i++) {
			if (serverCode == 200) {
				InputStream is = con.getInputStream();
				InputStreamReader inputStreamReader = new InputStreamReader(is);
				BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
				StringBuilder stringBuilder = new StringBuilder();
				String bufferedStrChunk = null;
				while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
					stringBuilder.append(bufferedStrChunk);
				}
				value = stringBuilder.toString();
				Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
				user = gson.fromJson(value, UserInfo.class);
				inputStreamReader.close();
				bufferedReader.close();
				break;
			} else if (serverCode == 401) {
				if(i == MAX_ATTEMPTS){
					break;
				}
				GoogleAuthUtil.invalidateToken(context, googleToken);
				Thread.sleep(backoff);
				backoff *= 2;
			} else {
				Log.e("Server returned the following error code: " + serverCode, null);
			}
		}
		return user;
	}
	
	public void loginGoogle(String accessToken, final String googleToken, final String email) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("google_email", email);
		params.put("google_access_token", googleToken);
		params.put("device_id", Utils.getDeviceId(context));
		params.put("device_os", deviceOSName);
		params.put("device_os_version", deviceOSVersion);
		String endpoint = Constants.LOGIN_GOOGLE_ENDPOINT + accessToken;
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
//                			JSONObject data = json.getJSONObject("data");
                			Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
                			AccessToken accessToken = gson.fromJson(json.toString(), AccessToken.class); 
                			accessToken.setGoogleEmail(email);
                			accessToken.setGoogleToken(googleToken);
        					eventBus.post(new Event.LoginGoogleSuccessEvent(accessToken));
                		} else {
                			eventBus.post(new Event.RequestFailEvent(json.getInt("error_code")));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "login google Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void loginFacebook(String accessToken, String facebookToken, String facebookEmail){
		PackageManager pm = context.getPackageManager();
		PackageInfo pi = null;
		try {
			pi = pm.getPackageInfo("com.gamota.mobi", 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		String clientVersion = pi.versionName;
		Map<String, String> params = new HashMap<String, String>();
		params.put("facebook_access_token", facebookToken);
		params.put("facebook_email", facebookEmail);
		params.put("device_id", Utils.getDeviceId(context));
		params.put("device_os", deviceOSName);
		params.put("device_os_version", deviceOSVersion);
		params.put("client_version", clientVersion);
		String endpoint = Constants.FB_LOGIN_ENDPOINT + accessToken;
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		if(status){
                			Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
                			AccessToken accessToken = gson.fromJson(json.toString(), AccessToken.class);
        					eventBus.post(new Event.LoginGoogleSuccessEvent(accessToken));
                		} else {
                			eventBus.post(new Event.RequestFailEvent(json.getInt("error_code")));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "login facebook Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void exchangeTYM(String accessToken, String tym){
		String endpoint = Constants.EXCHANGE_TYM_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		final ExchangeTymData data = new ExchangeTymData();
		params.put("red", tym);
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		boolean status = json.getBoolean("status");
                		String message = json.getString("message");
                		if(status){
        					JSONObject dataObj = json.getJSONObject("data");
        					int greenTym = dataObj.getInt("tym");
        					int purpleTym = dataObj.getInt("purple_tym");
        					data.setStatus(status);
        					data.setGreenTym(greenTym);
        					data.setMessage(message);
        					data.setPurpleTym(purpleTym);
        					eventBus.post(new Event.ExchangeTYMSuccessEvent(data));
                		} else {
                			eventBus.post(new Event.ExchangeTYMFailEvent(message));
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "exchange tym Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
//	public void getFeedList(String store, int start, int limit){
//		String endpoint = Constants.NEWSFEED_ENDPOINT;
//		Map<String, String> params = new HashMap<String, String>();
//		params.put("store", store);
//		params.put("start", String.valueOf(start));
//		params.put("limit", String.valueOf(limit));
//		final List<FeedItem> feedList = new ArrayList<FeedItem>();
//		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
//            @Override
//            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
//                if(json != null){
//                	try {
//        				boolean status = json.getBoolean("status");
//        				if(status){
//        					JSONArray array = json.getJSONArray("data");
//        					Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
//        					FeedItem feed;
//        					for(int j=0; j < array.length(); j++){
//        						JSONObject feedObj = array.getJSONObject(j);
//        						feed = gson.fromJson(feedObj.toString(), FeedItem.class);
//        						feedList.add(feed);
//        					}
//        					eventBus.post(new Event.FeedListSuccessEvent(feedList));
//        				} else {
//        					eventBus.post(new Event.FeedListFailEvent(json.getString("message")));
//        				}
//					} catch (JSONException e) {
//						e.printStackTrace();
//						eventBus.post(new Event.RequestFailEvent(-2));
//					}
//                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
//                } else {
//                	Log.e(TAG, "Error: " + ajaxStatus.getCode());
//                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
//                }
//            }
//		});
//	}
	
	public void getFBFeedList(int limit){
		String url = "https://graph.facebook.com/fql?q=";
		String params = "select object_id,caption,src_big,like_info,comment_info FROM photo WHERE owner = '214557388625397' and (strpos(caption, '[News]') >=0 or strpos(caption, '[sNews]') >= 0) LIMIT " + limit;
		final List<FBFeedItem> feedList = new ArrayList<FBFeedItem>();
		String endpoint = "";
		try {
			endpoint = url + URLEncoder.encode(params, "UTF-8");
			System.err.println("feedlist: " + endpoint);
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		aq.ajax(endpoint, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		JSONArray array = json.getJSONArray("data");
    					JSONObject obj;
    					FBFeedItem item = null;
    					JSONObject likeObj;
    					JSONObject commentsObj;
    					if(array.length() > 0){
    						for(int i = 0; i < array.length(); i++){
    							obj = array.getJSONObject(i);
    							item = new FBFeedItem();
    							item.setId(obj.getString("object_id"));
    							item.setMessage(obj.getString("caption"));
    							item.setPictureURL(obj.getString("src_big"));
    							likeObj = obj.getJSONObject("like_info");
    							item.setLikeCount(likeObj.getInt("like_count"));
    							item.setCanLike(likeObj.getBoolean("can_like"));
    							item.setUserLike(likeObj.getBoolean("user_likes"));
    							commentsObj = obj.getJSONObject("comment_info");
    							item.setCommentCount(commentsObj.getInt("comment_count"));
    							if(item.getMessage().contains("[sNews]")){
    								item.setOrder(1);
    							} else {
    								item.setOrder(2);
    							}
    							feedList.add(item);
    						}
    					}
    					eventBus.post(new Event.FeedListSuccessEvent(feedList));
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "get fb feed list Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void like(String accessToken, String objectId){
		String endpoint = "https://graph.facebook.com/" + objectId + "/likes?method=POST&access_token=" + accessToken;
		aq.ajax(endpoint, String.class, new AjaxCallback<String>() {
            @Override
            public void callback(String url, String result, AjaxStatus ajaxStatus) {
                if(result != null){
                	if(result.equalsIgnoreCase("true")){
                		eventBus.post(new Event.LikeSuccessEvent());
                	} else {
                		eventBus.post(new Event.LikeFailEvent());
                	}
                    Log.d(TAG, "Like:" + result);
                } else {
                	Log.e(TAG, "Like: " + ajaxStatus.getCode());
                }
            }
		});
	}
	
	public void unlike(String accessToken, String objectId){
		String endpoint = "https://graph.facebook.com/" + objectId + "/likes?method=DELETE&access_token=" + accessToken;
		aq.ajax(endpoint, String.class, new AjaxCallback<String>() {
            @Override
            public void callback(String url, String result, AjaxStatus ajaxStatus) {
                if(result != null){
                	if(result.equalsIgnoreCase("true")){
                		eventBus.post(new Event.UnLikeSuccessEvent());
                	} else {
                		eventBus.post(new Event.UnLikeFailEvent());
                	}
                    Log.d(TAG, "UnLike:" + result);
                } else {
                	Log.e(TAG, "UnLike: " + ajaxStatus.getCode());
                }
            }
		});
	}
	
	public void commentFB(String accessToken, String objectId, String message){
		String endpoint = "https://graph.facebook.com/" + objectId + "/comments";
		//String params = "comments?method=POST&access_token=" + accessToken + "&message=" + message;
		Map<String, String> params = new HashMap<String, String>();
		params.put("access_token", accessToken);
		params.put("message", message);
//		try {
//			endpoint = endpoint + URLEncoder.encode(params, "UTF-8").toString();
//			System.err.println(endpoint);
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		}
		aq.ajax(endpoint, params, String.class, new AjaxCallback<String>() {
            @Override
            public void callback(String url, String result, AjaxStatus ajaxStatus) {
                if(result != null){
                	eventBus.post(new Event.CommentFBSuccess());
                    Log.d(TAG, "CommentFB:" + result);
                } else {
                	eventBus.post(new Event.CommentFBFail());
                	Log.e(TAG, "CommentFB: " + ajaxStatus.getCode());
                }
            }
		});
	}
	
	public void getFeedDetailsLikes(String objectId){
		String url = "https://graph.facebook.com/fql?q=";
		String params = "{'like_data':'select user_id from like WHERE object_id = " + objectId + "', 'user_data':'select uid,name,pic from user WHERE uid IN (SELECT user_id from #like_data)','like_count':'select like_info from photo WHERE object_id = 473338552747278'}";
		String endpoint = "";
		try {
			endpoint = url + URLEncoder.encode(params, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		aq.ajax(endpoint, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		JSONArray array = json.getJSONArray("data");
                		FBLikes fbLikes = new FBLikes();
    					JSONObject likeCount = array.getJSONObject(0);
    					if(likeCount.getString("name").equalsIgnoreCase("like_count")){
    						JSONArray likeCountArr = likeCount.getJSONArray("fql_result_set");
    						JSONObject obj = likeCountArr.getJSONObject(0);
    						JSONObject likeInfo = obj.getJSONObject("like_info");
    						fbLikes.setLikeCount(likeInfo.getInt("like_count"));
    						fbLikes.setUserLikes(likeInfo.getBoolean("user_likes"));
    					}
    					JSONObject likeData = array.getJSONObject(1);
    					List<FBUser> userList = new ArrayList<FBFeedItem.FBUser>();
    					if(likeData.getString("name").equalsIgnoreCase("like_data")){
    						JSONArray likeDataArr = likeData.getJSONArray("fql_result_set");
    						JSONObject userIdObj;
    						FBUser user;
    						for(int i = 0; i < likeDataArr.length(); i++){
    							userIdObj = likeDataArr.getJSONObject(i);
    							user = new FBUser();
    							user.setId(userIdObj.getString("user_id"));
    							userList.add(user);
    						}
    					}
    					JSONObject userData = array.getJSONObject(2);
    					if(userData.getString("name").equalsIgnoreCase("user_data")){
    						JSONArray userDataArr = userData.getJSONArray("fql_result_set");
    						JSONObject userObj;
    						for(int i = 0; i < userDataArr.length(); i++){
    							userObj = userDataArr.getJSONObject(i);
    							userList.get(i).setName(userObj.getString("name"));
    							userList.get(i).setPic(userObj.getString("pic"));
    						}
    					}
    					fbLikes.setLikesPersons(userList);
    					eventBus.post(new Event.GetFeedLikesSuccess(fbLikes));
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "get feedback details like Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void getFeedComments(String id, int limit){
		String url = "https://graph.facebook.com/fql?q=";
		String params = "{'comment_data':'select id,text,likes,fromid,user_likes,time from comment WHERE object_id = " + id + " LIMIT " + limit + "', 'user_data':'select uid,name,pic from user WHERE uid IN (SELECT fromid from #comment_data)'}";
		String endpoint = "";
		try {
			endpoint = url + URLEncoder.encode(params, "UTF-8").toString();
			System.err.println(endpoint);
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		final List<FBComments> comments = new ArrayList<FBFeedItem.FBComments>();
		aq.ajax(endpoint, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		FBComments fbComment;
                		JSONObject cmObj;
                		JSONObject uObj;
                		JSONArray dataArr = json.getJSONArray("data");
                		if(dataArr.length() > 0){
                			JSONObject commentObj = dataArr.getJSONObject(0);
                			if(commentObj.getString("name").equalsIgnoreCase("comment_data")){
                				JSONArray commentArr = commentObj.getJSONArray("fql_result_set");
                				for(int i = 0; i < commentArr.length(); i++){
                					cmObj = commentArr.getJSONObject(i);
                					fbComment = new FBComments();
                					fbComment.setId(cmObj.getString("id"));
                					fbComment.setContent(cmObj.getString("text"));
                					fbComment.setLikeCount(cmObj.getInt("likes"));
                					fbComment.setFromId(cmObj.getString("fromid"));
                					fbComment.setUserLike(cmObj.getBoolean("user_likes"));
                					fbComment.setTime(cmObj.getLong("time"));
                					comments.add(fbComment);
                				}
                			}
                			JSONObject userObj = dataArr.getJSONObject(1);
                			if(userObj.getString("name").equalsIgnoreCase("user_data")){
                				JSONArray userArr = userObj.getJSONArray("fql_result_set");
                				for(int i = 0; i < userArr.length(); i++){
                					uObj = userArr.getJSONObject(i);
                					for(FBComments comment : comments){
                    					if(comment.getFromId().equalsIgnoreCase(uObj.getString("uid"))){
                    						comment.setAvatar(uObj.getString("pic"));
                    						comment.setName(uObj.getString("name"));
                    					}
                					}
                				}
                			}
                			eventBus.post(new Event.getFeedCommentSuccess(comments));
                		} else {
                			eventBus.post(new Event.getFeedCommentFail());
                		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "FB Comment Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void getCollectionGroup(String accessToken, String store){
		String endpoint = Constants.COLLECTION_GROUP_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("store", store);
		params.put("client", CLIENT_TYPE);
		final List<CollectionGroup> groupList = new ArrayList<CollectionGroup>();
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
					try {
						boolean status = json.getBoolean("status");
						if(status){
							JSONObject obj = json.getJSONObject("data");
							JSONArray array = obj.getJSONArray("data");
							JSONObject groupObj;
							CollectionGroup group;
							Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
							for(int i=0; i<array.length(); i++){
								groupObj = array.getJSONObject(i);
								group = gson.fromJson(groupObj.toString(), CollectionGroup.class);
								groupList.add(group);
							}
							eventBus.post(new Event.CollectionGroupEvent(groupList));
						} else {
							eventBus.post(new Event.HomeScreenFailEvent(json.getInt("error_code")));
						}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.HomeScreenFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "get collection group Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.HomeScreenFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void getAllCollections(String str){
		JSONObject json;
		try {
			json = new JSONObject(str);
			final List<CollectionList> collectionList = new ArrayList<CollectionList>();
			if(json != null){
	        	boolean status;
				try {
					status = json.getBoolean("status");
					if(status){
						JSONObject obj = json.getJSONObject("data");
						JSONArray array = obj.getJSONArray("data");
						JSONObject collObj;
						JSONArray contentArr;
						JSONObject contentObj;
						ContentItemInfo item;
						CollectionList collList;
						List<ContentItemInfo> contentList;
						
						if(array.length() > 0){
							for(int i=0; i<array.length(); i++){
								collList = new CollectionList();
								collObj = array.getJSONObject(i);
								collList.setCover(collObj.getString("cover"));
								collList.setId(collObj.getInt("collection_id"));
								collList.setType(collObj.getString("type"));
								collList.setName(collObj.getString("name"));
								collList.setOrder(collObj.getInt("order"));
								
								contentArr = collObj.getJSONArray("contents");
								contentList = new ArrayList<ContentItemInfo>();
								if(contentArr.length() > 0){
									for(int j=0; j<contentArr.length(); j++){
										contentObj = contentArr.getJSONObject(j);
										item = new ContentItemInfo();
										item.setAvatar(contentObj.getString("avatar"));
										item.setTitle(contentObj.getString("title"));
										item.setPrice(contentObj.getInt("price"));
										int totalRate = contentObj.getInt("total_rate");
										int sumRate = contentObj.getInt("sum_rate");
										item.setApplicationId(contentObj.getString("application_id"));
										item.setPackageName(contentObj.getString("identifier_bundle"));
										item.setGiftbox(contentObj.getInt("giftbox"));
			            				item.setGiftboxDaysToGet(contentObj.getInt("giftbox_days_to_get"));
										if(totalRate > 0){
											item.setRating(sumRate / totalRate);
										} else {
											item.setRating(0);
										}
										contentList.add(item);
									}
									collList.setContentList(contentList);
									collectionList.add(collList);
								}
							}
							eventBus.post(new Event.AllCollectionsEvent(collectionList));
						} else {
							eventBus.post(new Event.EmptyEvent());
						}
					} else {
	            		eventBus.post(new Event.HomeScreenFailEvent(json.getInt("error_code")));
	            	}
				} catch (JSONException e) {
					e.printStackTrace();
					eventBus.post(new Event.HomeScreenFailEvent(-2));
				}
	        }
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
	}
	
	public void getLevel2CollectionList(String accessToken, String store, int groupId){
		String endpoint = Constants.LEVEL2_COLLECTION_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("store", store);
		params.put("client", CLIENT_TYPE);
		params.put("group_id", String.valueOf(groupId));
		final List<CollectionList> collectionList = new ArrayList<CollectionList>();
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	boolean status;
					try {
						status = json.getBoolean("status");
						if(status){
							JSONObject obj = json.getJSONObject("data");
							JSONArray array = obj.getJSONArray("data");
							JSONObject collObj;
							JSONArray contentArr;
							JSONObject contentObj;
							ContentItemInfo item;
							CollectionList collList;
							List<ContentItemInfo> contentList;
							
							if(array.length() > 0){
								for(int i=0; i<array.length(); i++){
									collList = new CollectionList();
									collObj = array.getJSONObject(i);
									collList.setCover(collObj.getString("cover"));
									collList.setId(collObj.getInt("collection_id"));
									collList.setType(collObj.getString("type"));
									collList.setName(collObj.getString("name"));
									collList.setOrder(collObj.getInt("order"));
									
									contentArr = collObj.getJSONArray("contents");
									contentList = new ArrayList<ContentItemInfo>();
									if(contentArr.length() > 0){
										for(int j=0; j<contentArr.length(); j++){
											contentObj = contentArr.getJSONObject(j);
											item = new ContentItemInfo();
											item.setAvatar(contentObj.getString("avatar"));
											item.setTitle(contentObj.getString("title"));
											item.setPrice(contentObj.getInt("price"));
											int totalRate = contentObj.getInt("total_rate");
											int sumRate = contentObj.getInt("sum_rate");
											item.setApplicationId(contentObj.getString("application_id"));
											item.setPackageName(contentObj.getString("identifier_bundle"));
											item.setGiftbox(contentObj.getInt("giftbox"));
				            				item.setGiftboxDaysToGet(contentObj.getInt("giftbox_days_to_get"));
											if(totalRate > 0){
												item.setRating(sumRate / totalRate);
											} else {
												item.setRating(0);
											}
											contentList.add(item);
										}
										collList.setContentList(contentList);
										collectionList.add(collList);
									}
								}
								eventBus.post(new Event.Level2CollectionListEvent(collectionList, json.toString()));
							} else {
								eventBus.post(new Event.EmptyEvent());
							}
						} else {
	                		eventBus.post(new Event.HomeScreenFailEvent(json.getInt("error_code")));
	                	}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.HomeScreenFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "get level 2 collection list Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.HomeScreenFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void getLevel3CollectionList(String accessToken, String store, int listId){
		final DatabaseHelper db = new DatabaseHelper(context);
		String endpoint = Constants.LEVEL3_COLLECTION_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("store", store);
		params.put("client", CLIENT_TYPE);
		params.put("list_id", String.valueOf(listId));
		final List<CollectionList> collectionList = new ArrayList<CollectionList>();
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
            	if(json != null){
                	boolean status;
					try {
						status = json.getBoolean("status");
						if(status){
							JSONObject obj = json.getJSONObject("data");
							JSONArray array = obj.getJSONArray("data");
							JSONObject collObj;
							JSONArray contentArr;
							JSONObject contentObj;
							ContentItemInfo item;
							CollectionList collList;
							List<ContentItemInfo> contentList;
							for(int i = 0; i < array.length(); i++){
								collList = new CollectionList();
								collObj = array.getJSONObject(i);
								collList.setCover(collObj.getString("cover"));
								collList.setId(collObj.getInt("collection_id"));
								collList.setType(collObj.getString("type"));
								collList.setName(collObj.getString("name"));
								
								contentList = new ArrayList<ContentItemInfo>();
								
								contentArr = collObj.getJSONArray("contents");
								for(int j = 0; j < contentArr.length(); j++){
									contentObj = contentArr.getJSONObject(j);
									item = new ContentItemInfo();
									item.setAvatar(contentObj.getString("avatar"));
									item.setTitle(contentObj.getString("title"));
									item.setPrice(contentObj.getInt("price"));
									int totalRate = contentObj.getInt("total_rate");
									int sumRate = contentObj.getInt("sum_rate");
									item.setAuthor(contentObj.getString("author"));
									item.setApplicationId(contentObj.getString("application_id"));
									item.setPackageName(contentObj.getString("identifier_bundle"));
									item.setGiftbox(contentObj.getInt("giftbox"));
		            				item.setGiftboxDaysToGet(contentObj.getInt("giftbox_days_to_get"));
									if(totalRate > 0){
										item.setRating(sumRate / totalRate);
									} else {
										item.setRating(0);
									}
									if(db.checkAppInstalled(item.getPackageName())){
	                					item.setInstalled(true);
	                				} else {
	                					item.setInstalled(false);
	                				}
									contentList.add(item);
								}
								collList.setContentList(contentList);
								collectionList.add(collList);
							}
							eventBus.post(new Event.Level3CollectionListEvent(collectionList));
	                	} else {
	                		eventBus.post(new Event.RequestFailEvent(json.getInt("error_code")));
	                	}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "get level 3 collection list Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void getCollectionContent(String accessToken, int collectionId, String filter){
		final DatabaseHelper db = new DatabaseHelper(context);
		String endpoint = Constants.COLLECTION_CONTENT_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("client", CLIENT_TYPE);
		params.put("collection_id", String.valueOf(collectionId));
		params.put("filter", filter);
		final List<ContentItemInfo> listContent = new ArrayList<ContentItemInfo>();
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
            	if(json != null){
            		try {
						boolean status = json.getBoolean("status");
						if(status){
							JSONObject obj = json.getJSONObject("data");
							JSONArray array = obj.getJSONArray("data");
							JSONObject contentObj;
							ContentItemInfo item;
							Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
							for(int i = 0; i < array.length(); i++){
								contentObj = array.getJSONObject(i);
								item = gson.fromJson(contentObj.toString(), ContentItemInfo.class);
								if(db.checkAppInstalled(item.getPackageName())){
                					item.setInstalled(true);
                				} else {
                					item.setInstalled(false);
                				}
                				listContent.add(item);
							}
							eventBus.post(new Event.CollectionContentSuccessEvent(listContent));
						} else {
							eventBus.post(new Event.HomeScreenFailEvent(json.getInt("error_code")));
						}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.HomeScreenFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "Error: get collection content " + ajaxStatus.getCode());
                	eventBus.post(new Event.HomeScreenFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void buyTYMViaSMS(final String from, String accessToken){
		String endpoint = Constants.SMS_TOPUP_ENDPOINT + accessToken;
		final List<SMSOption> smsOptions = new ArrayList<SMSOption>();
		aq.ajax(endpoint, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
            	if(json != null){
            		try {
						boolean status = json.getBoolean("status");
						if(status){
							SMSPayment data = new SMSPayment();
							JSONObject dataObj = json.getJSONObject("data");
							String topupId = dataObj.getString("topup_id");
							JSONArray smsArray = dataObj.getJSONArray("options");
							JSONObject smsObj;
							for(int j=0;j<smsArray.length();j++){
								smsObj = smsArray.getJSONObject(j);
								double amount = smsObj.getDouble("amount");
								if(amount > 4000){
									SMSOption option = new SMSOption();
									option.setAmount(amount);
									option.setCurrency(smsObj.getString("currency"));
									option.setSendNumber(smsObj.getString("send"));
									option.setSyntax(smsObj.getString("sms"));
									option.setTym(smsObj.getInt("tym"));
									smsOptions.add(option);
								}
							}
							data.setTransactionID(topupId);
							data.setSmsOptions(smsOptions);
							eventBus.post(new Event.TYMSMSEvent(data, from));
						} else {
							eventBus.post(new Event.SMSTYMFailEvent(json.getInt("error_code")));
						}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.SMSTYMFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "Error: buy TYM via SMS" + ajaxStatus.getCode());
                	eventBus.post(new Event.SMSTYMFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void buyTYMViaCard(final String from, String accessToken, String cardSerial, String cardCode, String vendor){
		String endpoint = Constants.CARD_TOPUP_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("vendor", vendor);
		params.put("card_serial", cardSerial);
		params.put("card_code", cardCode);
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
            	if(json != null){
            		boolean status;
					try {
						JSONObject obj = json.getJSONObject("data");
						status = json.getBoolean("status");
						if(status){
							eventBus.post(new Event.CardSuccessEvent(obj.getString("topup_id"), from));
	            		} else {
	            			eventBus.post(new Event.RequestFailEvent(json.getInt("error_code")));
	            		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	eventBus.post(new Event.RequestFailEvent(ajaxStatus.getCode()));
                	Log.e(TAG, "Error: buy TYM Via Card " + ajaxStatus.getCode());
                }
            }
		});
	}
	
	public void buyTYMViaBank(String accessToken, String amount){
		String endpoint = Constants.BANK_TOPUP_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("amount", amount);
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
            	if(json != null){
            		JSONObject obj;
					try {
						boolean status = json.getBoolean("status");
						if(status){
							obj = json.getJSONObject("data");
							BankPayment data = new BankPayment();
		            		BankOption option;
		        			for(int j=0; j< obj.length(); j++){
		        				String topupId = obj.getString("topup_id");
		        				JSONArray smsArray = obj.getJSONArray("options");
		        				for(int k=0;k<smsArray.length();k++){
		        					JSONObject smsObj = smsArray.getJSONObject(k);
		        					
		        					String bankUrl = smsObj.getString("url");
		        					String bankName = smsObj.getString("bank");
		        					int tym = smsObj.getInt("tym");
		        					double payAmount = smsObj.getDouble("amount");
		        					String currency = smsObj.getString("currency");
		        					
		        					option = new BankOption();
		        					option.setAmount(payAmount);
		        					option.setCurrency(currency);
		        					option.setUrl(bankUrl);
		        					option.setBank(bankName);
		        					option.setTym(tym);
		        					
		        					data.setTopupId(topupId);
		        					data.setOption(option);
		        				}
		        			}
		        			eventBus.post(new Event.TYMBankSuccessEvent(data));
						} else {
							eventBus.post(new Event.BankTYMFailEvent(json.getInt("error_code")));
						}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.BankTYMFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "buy tym via bank Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.BankTYMFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void buyTYMViaPaypal(String accessToken, final String amount){
		String endpoint = Constants.PAYPAL_TOPUP_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("amount", amount);
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
            	if(json != null){
					try {
						boolean status = json.getBoolean("status");
						if(status){
							PaypalPayment data = new PaypalPayment();
							PaypalForm form = new PaypalForm();
							JSONObject obj = json.getJSONObject("data");
		        			for(int j=0; j< obj.length(); j++){
		        				String topupId = obj.getString("topup_id");
		        				JSONArray paypalArray = obj.getJSONArray("options");
		        				for(int k=0;k<paypalArray.length();k++){
		        					JSONObject paypalObj = paypalArray.getJSONObject(k);
		        					for(int n=0;n<paypalObj.length();n++){
		        						JSONObject paypalForm = paypalObj.getJSONObject("form");
		        						String cmd = paypalForm.getString("cmd");
		        						int noShipping = paypalForm.getInt("no_shipping");
		        						int noNote = paypalForm.getInt("no_note");
		        						String currencyCode = paypalForm.getString("currency_code");
		        						String bn = paypalForm.getString("bn");
		        						String itemName = paypalForm.getString("item_name");
		        						String notifyUrl = paypalForm.getString("notify_url");
		        						String business = paypalForm.getString("business");
		        						
		        						form.setAmount(Double.valueOf(amount));
		        						form.setBn(bn);
		        						form.setBusiness(business);
		        						form.setCmd(cmd);
		        						form.setCurrencyCode(currencyCode);
		        						form.setItemName(itemName);
		        						form.setNoNote(noNote);
		        						form.setNoShopping(noShipping);
		        						form.setNotifyUrl(notifyUrl);
		        					}
		        					int tym = paypalObj.getInt("tym");
		        					String currency = paypalObj.getString("currency");
		        					
		        					data.setAmount(Double.valueOf(amount));
		        					data.setCurrency(currency);
		        					data.setForm(form);
		        					data.setTopupId(topupId);
		        					data.setTym(tym);
		        					data.setErrorCode(0);
		        				}
		        			}
		        			eventBus.post(new Event.TYMPaypalSuccessEvent(data));
						} else {
							eventBus.post(new Event.PaypalTYMFailEvent(json.getInt("error_code")));
						}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.PaypalTYMFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
                } else {
                	Log.e(TAG, "by tym via paypal Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.PaypalTYMFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
//	public void checkTopup(String accessToken, String topupId){
//		String endpoint = Constants.CHECK_TOPUP_ENDPOINT + accessToken;
//		Map<String, String> params = new HashMap<String, String>();
//		params.put("topup_id", topupId);
//		long backoff = 2000 + new Random().nextInt(1000);
//		String value = "";
//		TopupResult result = new TopupResult();
//		result.setErrorCode(-3);
//		for (int i = 1; i <= 10; i++) {
//            try {
//            	value = post(endpoint, params);
//            	Log.d(TAG, "CheckTopupTransaction. TopupID = [" + topupId + "] ------> " + value);
//            	JSONObject jsonObj = new JSONObject(value);
//            	boolean isSuccess = jsonObj.getBoolean("status");
//            	int errorCode = jsonObj.getInt("error_code");
//            	if(errorCode == 0){
//    				JSONObject dataObj = jsonObj.getJSONObject("data");
//    				String amount = dataObj.getString("tym");
//    				String msg = dataObj.getString("message");
//    				String time = dataObj.getString("time");
//    				String id = dataObj.getString("topup_id");
//    				result.setStatus(isSuccess);
//    				result.setMessage(msg);
//    				result.setAmount(amount);
//    				result.setErrorCode(errorCode);
//    				result.setId(id);
//    				result.setTime(time);
//    				eventBus.post(new Event.TopupSuccessEvent(result));
//    			} else if(errorCode == 9){
//    				Thread.sleep(backoff);
//    				backoff *= 2;
//    			} else {
//    				eventBus.post(new Event.TopupFailEvent(errorCode));
//    			}
//            } catch (IOException e) {
//            	Log.e(TAG, "Failed to connect on attempt " + i + ":" + e);
//                if (i == 5) {
//                	eventBus.post(new Event.TopupFailEvent(-4));
//                }
//                try {
//                     Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
//                     Thread.sleep(backoff);
//                } catch (InterruptedException e1) {
//                     Thread.currentThread().interrupt();
//                     eventBus.post(new Event.TopupFailEvent(-1));
//                 }
//                 backoff *= 2;
//			} catch (JSONException e) {
//				eventBus.post(new Event.TopupFailEvent(-2));
//			} catch (InterruptedException e) {
//                Thread.currentThread().interrupt();
//                eventBus.post(new Event.TopupFailEvent(-1));
//			}
//		}
//	}
	
	public void createUserSettings(String accessToken, final String settingName, final String content, int permission){
		String endpoint = Constants.USER_CREATE_SETTINGS_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("setting", settingName);
		params.put("content", content);
		params.put("permission", String.valueOf(permission));
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
            	if(json != null){
            		boolean status;
					try {
						status = json.getBoolean("status");
						if(status){
	            			eventBus.post(new Event.CreateUserSettingSuccess());
	            		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.CreateUserSettingSuccess());
					}
                    Log.d(TAG, ajaxStatus.getCode() + "create setting :" + json.toString());
                } else {
                	Log.e(TAG, "create setting: " + ajaxStatus.getCode());
                	eventBus.post(new Event.CreateUserSettingFail(settingName, content));
                }
            }
		});
	}
	
	public void updateUserSetting(String accessToken, String settingName, String content, int permission){
		String endpoint = Constants.USER_UPDATE_SETTINGS_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("setting", settingName);
		params.put("content", content);
		params.put("permission", String.valueOf(permission));
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
            	if(json != null){
                    Log.d(TAG, ajaxStatus.getCode() + "update setting :" + json.toString());
                } else {
                	Log.e(TAG, "update setting: " + ajaxStatus.getCode());
                }
            }
		});
	}
	
	public void getUsetSettingList(String accessToken){
		String endpoint = Constants.USER_LIST_SETTINGS_ENDPOINT + accessToken;
		final List<String> settingNames = new ArrayList<String>();
		aq.ajax(endpoint, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
            	if(json != null){
            		boolean status;
					try {
						status = json.getBoolean("status");
	            		if(status){
	            			JSONObject data = json.getJSONObject("data");
	            			JSONArray array = data.getJSONArray("settings");
	            			JSONObject settingObj = null;
	            			String name = null;
	            			for (int i = 0; i < array.length(); i++) {
								settingObj = array.getJSONObject(i);
								name = settingObj.getString("setting_name");
								if(name.startsWith("gift")){
									settingNames.add(name);
								}
							}
	            			eventBus.post(new Event.GetSettingListSuccess(settingNames));
	            		} else {
	            			eventBus.post(new Event.GetSettingListFail(json.getInt("error_code")));
	            		}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.GetSettingListFail(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + "list setting:" + json.toString());
                } else {
                	Log.e(TAG, "list setting: " + ajaxStatus.getCode());
                	eventBus.post(new Event.GetSettingListFail(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void getSettingDetails(String accessToken, String settingName, String key){
		String endpoint = Constants.USER_DETAILS_SETTINGS_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("setting", settingName);
		if(key != null){
			params.put("key", key);
		}
		final GiftSetting gs = new GiftSetting();
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
            	if(json != null){
            		try {
						boolean status = json.getBoolean("status");
						if(status){
							JSONObject data = json.getJSONObject("data");
							String setting = data.getString("settings");
							JSONObject settingObj = new JSONObject(setting);
							gs.setDays(settingObj.getInt("days"));
							gs.setReceived(settingObj.getInt("received"));
							gs.setName(settingObj.getString("name"));
							eventBus.post(gs);
						} else {
							eventBus.post(new RequestFailEvent(json.getInt("error_code")));
						}
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new RequestFailEvent(-2));
					}
                    Log.d(TAG, ajaxStatus.getCode() + "details setting :" + json.toString());
                } else {
                	Log.e(TAG, "details setting: " + ajaxStatus.getCode());
                	eventBus.post(new RequestFailEvent(ajaxStatus.getCode()));
                }
            }
		});
	}
	
	public void getAllSettingDetails(String accessToken, List<String> nameList){
		String endpoint = Constants.USER_DETAILS_SETTINGS_ENDPOINT + accessToken;
		Map<String, String> params;
		final List<GiftSetting> giftList = new ArrayList<GiftSetting>();
		String value;
		int count = 0;
		GiftSetting gs = null;
		for(String name : nameList){
			params = new HashMap<String, String>();
			params.put("setting", name);
			try {
				value = post(endpoint, params);
				System.out.println("asd: " + value);
				count++;
				JSONObject json = new JSONObject(value);
				boolean status = json.getBoolean("status");
        		if(status){
        			JSONObject data = json.getJSONObject("data");
					String setting = data.getString("settings");
					String received;
					String slug;
					if(setting.contains(":")){
						String[] dataStr = setting.split(":");
						slug = dataStr[0];
						received = dataStr[1];
					} else {
						received = setting;
						slug = "null";
					}
					gs = new GiftSetting();
					gs.setReceived(Integer.parseInt(received));
					gs.setSlug(slug);
					giftList.add(gs);
        		}
			} catch (IOException e) {
				e.printStackTrace();
			}
			catch (JSONException e) {
				e.printStackTrace();
			}
		}
		if(count == nameList.size()){
			eventBus.post(new Event.GetSettingDetailsListSuccess(giftList));
		}
	}
	
	public void getUserGiftboxList(String accessToken){
		String endpoint = Constants.USER_GET_GIFTBOX_LIST_ENDPOINT + accessToken;
		aq.ajax(endpoint, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
            	if(json != null){
                    Log.d(TAG, ajaxStatus.getCode() + "gift list :" + json.toString());
                } else {
                	Log.e(TAG, "gift list : " + ajaxStatus.getCode());
                }
            }
		});
	}
	
	public void openGiftbox(String accessToken, int giftboxId){
		String endpoint = Constants.USER_OPEN_GIFTBOX_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("gift_box_id", String.valueOf(giftboxId));
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
            	if(json != null){
                    Log.d(TAG, ajaxStatus.getCode() + "open gift :" + json.toString());
                } else {
                	Log.e(TAG, "open gift: " + ajaxStatus.getCode());
                }
            }
		});
	}
	
	public void buyGift(String accessToken, int itemId){
		String endpoint = Constants.USER_BUY_GIFTBOX_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("id", String.valueOf(itemId));
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
            	if(json != null){
                    Log.d(TAG, ajaxStatus.getCode() + "buy gift :" + json.toString());
                } else {
                	Log.e(TAG, "buy gift: " + ajaxStatus.getCode());
                }
            }
		});
	}
	
	public void reportInstall(String accessToken, String slug, int versionId, String status){
		String endpoint = Constants.REPORT_INSTALL_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("application_id", slug);
		//params.put("version_id", String.valueOf(versionId));
		params.put("status", status);
		params.put("device_id", Utils.getDeviceId(context));
		params.put("device_os", deviceOSName);
		params.put("device_os_version", deviceOSVersion);
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
            	if(json != null){
            		try {
						boolean status = json.getBoolean("status");
						if(status){
							eventBus.post(new Event.ReportInstallSuccess());
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
                    Log.d(TAG, ajaxStatus.getCode() + "report install :" + json.toString());
                } else {
                	eventBus.post(new Event.ReportInstallFail());
                	Log.e(TAG, "report install: " + ajaxStatus.getCode());
                }
            }
		});
	}
	
	public void reportGiftbox(String accessToken, final String slug, final String type, final String packageName){
		String endpoint = Constants.REPORT_GIFTBOX_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("application_id", slug);
		params.put("type", type);
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
            	if(json != null){
            		boolean status;
					try {
						status = json.getBoolean("status");
	            		if(status){
	            			if(type.equalsIgnoreCase("check")){
	            				Giftbox giftbox = new Giftbox();
		            			JSONObject data = json.getJSONObject("data");
		            			giftbox.setType(data.getString("type"));
		            			giftbox.setDesc(data.getString("description"));
		            			giftbox.setValue(data.getInt("value"));
		            			giftbox.setMessage(json.getString("message"));
		            			giftbox.setUsed(data.getInt("used"));
		            			giftbox.setSlug(slug);
		            			eventBus.post(new Event.ReportGiftboxSuccess(type, giftbox, packageName));
	            			} else if(type.equalsIgnoreCase("confirm")){
	            				eventBus.post(new Event.ConfirmGiftBoxSuccess(type, slug));
	            			}
	            		} else {
	            			eventBus.post(new Event.GiftboxNotExists(json.getString("message")));
	            		}
					} catch (JSONException e) {
						e.printStackTrace();
					}
                    Log.d(TAG, ajaxStatus.getCode() + "report gift :" + json.toString());
                } else {
                	Log.e(TAG, "report gift: " + ajaxStatus.getCode());
                	eventBus.post(new Event.ReportGiftboxFail(type));
                }
            }
		});
	}
	
	public void likedOrNot(String url, String facebookToken){
		String query = Constants.FB_FQL_QUERY + "'" + url + "'&access_token=" + facebookToken;
		String endpoint = Constants.FB_FQL_URL + query;
		aq.ajax(endpoint, JSONObject.class, new AjaxCallback<JSONObject>(){

			@Override
			public void callback(String url, JSONObject json, AjaxStatus status) {
				// TODO Auto-generated method stub
				try {
					JSONObject obj = null;
					JSONArray array = json.getJSONArray("data");
					for(int i = 0; i < array.length(); i++){
						obj = array.getJSONObject(i);
						String userId = obj.getString("user_id");
						if(!TextUtils.isEmpty(userId)){
							eventBus.post(new Event.LikedEvent());
						} else {
							eventBus.post(new Event.NotLikedEvent());
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
					eventBus.post(new Event.NotLikedEvent());
				}
			}
			
		});
	}
	
	public void checkRemainGift(String accessToken, String slug){
		String endpoint = Constants.CHECK_REMAIN_GIFT_ENDPOINT + accessToken;
		Map<String, String> params = new HashMap<String, String>();
		params.put("application_id", slug);
		aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>(){

			@Override
			public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
				// TODO Auto-generated method stub
				if(json != null){
					boolean status;
					try {
						status = json.getBoolean("status");
						if(status){
							JSONObject data = json.getJSONObject("data");
							int giftRemain = data.getInt("is_giftbox");
							if(giftRemain == 1){
								eventBus.post(new Event.HasGiftBox());
							} else {
								eventBus.post(new Event.OutOfGiftBox());
							}
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
					Log.d(TAG, ajaxStatus.getCode() + "check remain gift :" + json.toString());
				} else {
					eventBus.post(new Event.OutOfGiftBox());
				}
			}
			
		});
	}
	
//	public void like(String url, String facebookToken){
//		String endpoint = "https://graph.facebook.com/me/og.likes?method=POST&access_token=" + facebookToken + "&object=" + url;
//		aq.ajax(endpoint, JSONObject.class, new AjaxCallback<JSONObject>(){
//
//			@Override
//			public void callback(String url, JSONObject json, AjaxStatus status) {
//				// TODO Auto-generated method stub
//				if(json.toString().contains("id")){
//					eventBus.post(new Event.LikeSuccessEvent());
//				} else {
//					eventBus.post(new Event.LikeFailEvent());
//				}
//			}
//			
//		});
//	}
	
	public void getNumberOfLikes(final String url){
		String endpoint = "https://graph.facebook.com/?ids=" + url;
		aq.ajax(endpoint, JSONObject.class, new AjaxCallback<JSONObject>(){

			@Override
			public void callback(String link, JSONObject json, AjaxStatus status) {
				// TODO Auto-generated method stub
				try {
					JSONObject obj = json.getJSONObject(url);
					long likeNumber = obj.getLong("shares");
					eventBus.post(new Event.GetLikeNumberEvent(likeNumber));
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
		});
	}

	private String unsecurePost(String endpoint, Map<String, String> params)
			throws IOException {
		URL url;
		String returnValue = "";
		try {
			url = new URL(endpoint);
		} catch (MalformedURLException e) {
			throw new IllegalArgumentException("invalid url: " + endpoint);
		}
		StringBuilder bodyBuilder = new StringBuilder();
		Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
		// constructs the POST body using the parameters
		while (iterator.hasNext()) {
			Entry<String, String> param = iterator.next();
			bodyBuilder.append(param.getKey()).append('=')
					.append(param.getValue());
			if (iterator.hasNext()) {
				bodyBuilder.append('&');
			}
		}
		String body = bodyBuilder.toString();
		Log.v("TAG", "Posting '" + body + "' to " + url);
		byte[] bytes = body.getBytes();
		HttpURLConnection conn = null;
		Log.e("URL", "> " + url);
		conn = (HttpURLConnection) url.openConnection();
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		conn.setFixedLengthStreamingMode(bytes.length);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded;charset=UTF-8");
		// post the request
		OutputStream out = conn.getOutputStream();
		out.write(bytes);
		out.close();
		// handle the response
		int status = conn.getResponseCode();
		if (status != 200) {
			throw new IOException("Post failed with error code " + status);
		} else {
			InputStream in = new BufferedInputStream(conn.getInputStream());
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					in, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			in.close();
			returnValue = sb.toString();
		}
		return returnValue;
	}

	private String post(String endpoint, Map<String, String> params)
			throws IOException {
		String returnValue = "";
		HttpParams httpParameters = new BasicHttpParams();
		int timeoutConnection = 10000;
		HttpConnectionParams.setConnectionTimeout(httpParameters,
				timeoutConnection);
		int timeoutSocket = 10000;
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
		HttpClient client = HttpUtils.getNewHttpClient();
		HttpPost post = new HttpPost(endpoint);
		List<NameValuePair> paramList = new ArrayList<NameValuePair>();
		Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
		// constructs the POST body using the parameters
		BasicNameValuePair pair = null;
		while (iterator.hasNext()) {
			Entry<String, String> param = iterator.next();
			pair = new BasicNameValuePair(param.getKey(), param.getValue());
			paramList.add(pair);
		}
		try {
			UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
					paramList);
			post.setEntity(urlEncodedFormEntity);
			HttpResponse httpResponse;
			httpResponse = client.execute(post);
			InputStream inputStream = httpResponse.getEntity().getContent();
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream);
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);
			StringBuilder stringBuilder = new StringBuilder();
			String bufferedStrChunk = null;
			while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
				stringBuilder.append(bufferedStrChunk);
			}
			returnValue = stringBuilder.toString();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return returnValue;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return returnValue;
	}
	
	public static String getAppVersion(Context context) {
	    try {
	        PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
	        return packageInfo.versionName;
	    } catch (NameNotFoundException e) {
	        throw new RuntimeException("Could not get package name: " + e);
	    }
	}
	
		 
//		 private List<BasicNameValuePair> getLoginParams(String type, int cateId,  int storeId, final int start){
//			 List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
//			 String filter="";
//			 String version = "android_" + getAppVersion(context);
//			 if (Utils.isTablet(context)) {
//					params.add(new BasicNameValuePair("filter", "has_tablet"));
//					filter="has_tablet";
//				} else {
//					params.add(new BasicNameValuePair("filter", "no_tablet"));
//					filter="no_tablet";
//				}
//				String input = cateId + CLIENT_TYPE + filter + "20" + start + storeId + version + "AppStoreVnAndroidNative!@#";
//				String hash = Utils.generateHashMD5(input);
//		  
//		  if (Utils.isTablet(context)) {
//				params.add(new BasicNameValuePair("filter", "has_tablet"));
//			} else {
//				params.add(new BasicNameValuePair("filter", "no_tablet"));
//			}
//		  if (type.equalsIgnoreCase(context.getResources().getString(R.string.top_new))) {
//				params.add(new BasicNameValuePair("store_id", String.valueOf(storeId)));
//			} else if (type.equalsIgnoreCase(context.getResources().getString(R.string.top_download))) {
//				params.add(new BasicNameValuePair("store_id", String.valueOf(storeId)));
//			} else if (type.equalsIgnoreCase(context.getResources().getString(R.string.top_paid))) {
//				params.add(new BasicNameValuePair("store_id", String.valueOf(storeId)));
//			} else if (type.equalsIgnoreCase(context.getResources().getString(R.string.top_free))) {
//				params.add(new BasicNameValuePair("store_id", String.valueOf(storeId)));
//			} else if (type.equalsIgnoreCase(context.getResources().getString(R.string.hot_app))) {
//				params.add(new BasicNameValuePair("store_id", String.valueOf(storeId)));
//			}
//		  params.add(new BasicNameValuePair("store_id", String.valueOf(storeId)));
//		  params.add(new BasicNameValuePair("category_id", String.valueOf(cateId)));
//		  params.add(new BasicNameValuePair("start", String.valueOf(start)));
//		  params.add(new BasicNameValuePair("client", CLIENT_TYPE));
//		  params.add(new BasicNameValuePair("limit", "20"));
//		  params.add(new BasicNameValuePair("hash", hash));
//		  params.add(new BasicNameValuePair("v", version));
//		  return params;
//		 }
		 
		 public void getTorrentDownloadLink(String accessToken, final String slug) {
				String endpoint = Constants.GET_TORRENT_LINK_ENDPOINT + accessToken;
				Map<String, String> params = new HashMap<String, String>();
				params.put("slug", slug);
				params.put("access_token", accessToken);
				aq.ajax(endpoint, params, JSONObject.class, new AjaxCallback<JSONObject>() {
		            @Override
		            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
		                if(json != null){
		                	Log.e("getTDL","getTDL: "+json.toString());
		                	try {
		                		List<String> extraUrls = new ArrayList<String>();
		                		boolean status = json.getBoolean("status");
		                		if(status){
//		                			JSONObject obj = json.getJSONObject("data");
//		                			String downloadLink = obj.getString("download");
//		                			String type = obj.getString("type");
//		                			JSONArray extras = obj.getJSONArray("extras");
//		                			String extraDownloadLink = "";
//		                			if(extras.length() > 0){
//		                				for(int i=0; i<extras.length(); i++){
//		                					JSONObject extrasObj = extras.getJSONObject(i);
//		                    				extraDownloadLink = extrasObj.getString("download");
//		                    				extraUrls.add(extraDownloadLink);
//		                				}
//		                			}
//		                			DownloadLink download = new DownloadLink();
//		                			download.setDownload(downloadLink);
//		                			download.setExtraDownload(extraUrls);
//		                			download.setType(type);
		                			///
//		                			data:{torrent_link,magnet_link,version_id,version_name};
		                			///
		                			eventBus.post(new Event.GetTorrentDownloadLinkSuccess());
		                		} else {
		                			eventBus.post(new Event.GetTorrentDownloadLinkSuccess());
		                		}
							} catch (JSONException e) {
								e.printStackTrace();
								eventBus.post(new Event.GetTorrentDownloadLinkSuccess());
							}
		                    Log.d(TAG, ajaxStatus.getCode() + ":" + json.toString());
		                } else {
		                	Log.e(TAG, "get torent download link Error: " + ajaxStatus.getCode());
		                	eventBus.post(new Event.GetTorrentDownloadLinkSuccess());
		                }
		            }
				});
			}
		 
//		 	DownloadLink download = new DownloadLink();
//			download.setDownload(downloadLink);
//			download.setExtraDownload(extraUrls);
//			download.setType(type);
//			eventBus.post(new Event.GetDownloadLinkSuccess(download, "", slug));
			
}
